Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

forms

django

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

class PostForm(ModelForm):

    class Meta:
        model = Photo
        exclude = ['author','featured','published']

    def __init__(self, *args, **kwargs):
        published = kwargs.pop('published', None)
        super(PostForm, self).__init__(*args, **kwargs)
        if not user.is_staff:
           del self.fields['published']

view.py

def addpost(request):

    if request.method == 'POST': 
        form = PostForm(request.POST,request.FILES,user=request.user) 
        if form.is_valid():

            post = form.save(False)
            post.author = request.user
            form.save()

            return HttpResponseRedirect(reverse('insight.content.views.index', ))

    else:
        form = PostForm(user=request.user)


    ispost = True
    return render_to_response('form_add_place.html', {'form': form,'ispost':ispost},context_instance=RequestContext(request))
like image 909
Hamza Avatar asked Mar 28 '12 02:03

Hamza


2 Answers

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

like image 172
mattoc Avatar answered Oct 07 '22 08:10

mattoc


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']
like image 43
Burhan Khalid Avatar answered Oct 07 '22 08:10

Burhan Khalid