Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
How to render form fields conditionally in django

I have two user groups.
1. Writer
2. editors

If the user is logged in as a writer, display the `title` and `body` field of an Article model, if the user is logged in as an Editor, display `title` `body` and `approved` field so the Editor can approve the article by review it.

I need to implement this feature without using Django admin. how could I achieve this?


class Article(models.Model):
choices = (("review", "Review"))
title = models.CharField("Article title", max_length=200)
body = models.TextField()
writer = models.ForeignKey(User, on_delete=models.CASCADE)
status = models.CharField(
max_length=20,
choices=(
('reivew', 'review'),
('published', 'published')
)
)

def get_absolute_url(self):
reverse('article-detail', kwargs={
"pk": self.id
})


#views.py


class ArticleCreate(CreateView):
model = Article
# Don't need to define inside meta class
fields = ("title", "body")

# Override the form_valid method to populate your data.
def form_valid(self, form):
form.instance.writer = self.request.user
form.instance.status = "published"
return super(ArticleCreate, self).form_valid(form)

# Don't need success url
# get_absolute_url is already defined in model



Q. Where to write a logic to hide and display the `status` field based on user group type

if u.groups.filter(name="Editors").exists():
#display status field
else:
# hide status field.


I know I could do thisn using django admin, using this logic, but I want to implement using my own generic views and forms.

class ArticleAdmin(admin.ModelAdmin):
fields = ['title', 'body'] # here comes the fields open to all users

def change_view(self, request, object_id, extra_context=None): # override default admin change behaviour
if request.user in Editors: # an example
self.fields.append('status') # add field 2 to your `fields`





/r/django
https://redd.it/7hee2d