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)
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
- [Answered ]-Django DecimalField "." instead of ","
- [Answered ]-Where to put REST API in Django
- [Answered ]-Using jQuery to Read a JSON File Generated by Django's Serialization
- [Answered ]-Django installation on MS Windows, manage.py "Couldn't import Django"
- [Answered ]-Django is giving trouble on urls to catch and forward to a view. (slug fields)
Source:stackexchange.com