1

The below code removes certain values from a drop down menu. It works fine but I want to remove the value if the user lacks certain permissions. How can I access request.user in the ModelForm's constructor? Or is there a better way to accomplish what I am trying to do?

class AnnouncementModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(AnnouncementModelForm, self).__init__(*args, **kwargs)
        self.fields["category"].queryset = AnnouncementCategory.objects.filter(can_post=True)   

2 Answers 2

1

How can I access request.user in the ModelForm's constructor?

To use it in the Form constructor, just pass the request to it.

class AnnouncementModelForm(forms.ModelForm):

    def __init__(self, request, *args, **kwargs):
        super(AnnouncementModelForm, self).__init__(*args, **kwargs)
        qs = request.user.foreignkeytable__set.all()
        self.fields["category"].queryset = qs
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. Are you sure about that though? Because I am getting this TypeError: __init__() takes at least 2 non-keyword arguments (1 given)
Pass the "request" argument into the Class creation! How else does it get it? AnnouncementModelForm(request)
1

Ok here is how I solved it:

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "category" and not request.user.has_perm('can_post_to_all'):
        kwargs["queryset"] = AnnouncementCategory.objects.filter(can_post=True)
        return db_field.formfield(**kwargs)
    return super(AnnouncementAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.