1

Model Post has the boolean field moderation, which is intended for publishing after approval by admin users (which have user.is_staff as True.

There is a page "Post update", where an user (the author of the post) and admin users can updated the post info. I want that the field moderation (which is a checkbox) is shown only if the user is an admin (user.is_staff == True).

models.py

class Post(models.Model):
    ...
    moderation = models.BooleanField(default=True)
    ...

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body', 'logo']

views.py

class PostUpdateView(PermissionRequiredMixin, UpdateView):
    model = Post
    fields = ['title', 'body', 'logo']
    permission_required = 'post.can_mark_returned'

post_form.html

{% extends "base_generic.html" %}
{% block content %}
    <form action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <table>
            {{ form.as_table }}
        </table>
        <input type="submit" value="Submit" />
    </form>
{% endblock %}
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • 1
    Can you please edit your question to reformulate "I need the this attribut was only in user.is_staff on the page "Post update" "? It is currently difficult to understand what you need exactly – Antwane Jan 17 '19 at 15:48
  • Do you mean to say that you only want the checkbox "moderation" visible in the form when the logged in user is staff? – 9769953 Jan 17 '19 at 15:53
  • @9769953 yeah)) –  Jan 17 '19 at 16:05
  • Note: your class `PostForm` is never used, as the view `PostUpdateView` creates its own form class based on the specified fields. – Ralf Jan 17 '19 at 17:34
  • @Ralf Even in the case of creating a new record? –  Jan 17 '19 at 17:44
  • If you use `CreateView`, then that too builds its own form class if you specified the `fields` on that view. However, if you want to use your own form, you can specify it using the attribute `form_class`, just like [this example](https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/#basic-forms) in the docs shows – Ralf Jan 17 '19 at 17:46

1 Answers1

2

This similar question has some ideas for you.


I can also suggest overriding FormMixin.get_form_class() and using modelform_factory():

from django.forms import modelform_factory

class PostUpdateView(PermissionRequiredMixin, UpdateView):
    model = Post
    permission_required = 'post.can_mark_returned'

    def get_form_class(self)
        fields = ['title', 'body', 'logo']
        if self.request.user.is_staff:
            fields.append('moderation')

        return modelform_factory(
            self.model,
            fields=fields)
Ralf
  • 16,086
  • 4
  • 44
  • 68