Django : How to exclude form field if the user is staff?

前端 未结 2 608

How to exclude form fields if the user is not staff ? I tried this but didn\'t work , giving an error :

global name \'user\' is not defined



        
相关标签:
2条回答
  • 2021-02-20 05:48

    This can be achieved in the template when rendering the form. It will need to allow null values or have a default value in the model definition or alternatively have its validation overridden:

    <form method="post">{% csrf_token %}
        {% if request.user.is_staff %}
        <p>{{ form.published }}</p>
        {% endif %}
    
        <p>{{ form.author }}</p>
    
        <!-- ... your other fields -->
    </form>
    

    Similarly you can check for is_superuser or check permissions, see the docs: https://docs.djangoproject.com/en/dev/topics/auth/default/#permissions

    0 讨论(0)
  • 2021-02-20 05:58

    You need to pass it the user instance from your request - the model form doesn't have access to it.

    my_form = PostForm(user=request.user)

    Then, in your __init__:

    def __init__(self, *args, **kwargs):
        published = kwargs.pop('published', None)
        user = kwargs.pop('user', None)
        super(PostForm, self).__init__(*args, **kwargs)
        if not user.is_staff:
           del self.fields['published']
    
    0 讨论(0)
提交回复
热议问题