Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin- Limiting ForeignKey Field's choices

I've been working on my Django Project. I use custom Forms (a class called Form), and I've got a class called Restricted_Form. The point of this class is that an Admin user ("staff status" user") has the option restrict which users or groups can have access to the Forms/submit filled Forms:

#....models.py:
from django.contrib.auth.models import User, Group

class Restricted_Form(models.Model):
    Form = models.ForeignKey('forms.Form')
    Authorized_Users = models.ManyToManyField(User, blank=True)
    Authorized_Groups = models.ManyToManyField(Group, blank=True)
    user = models.ForeignKey(User, blank=True, null=True, related_name="restriction_owner")

"Form" itself has:

user = models.ForeignKey(User, blank=True, null=True)
#this is always the user who created it

My issue is limiting what the non-superuser admins can do. They should only be able to create Restricted_Form objects including a Form they have created themselves. In practice, when they create a Restricted_Form, only "Forms" that they have created themselves should appear as options to select, in the drop-down menu. This is my related admin class right now:

#...admin.py
class RestrictedFormAdmin(admin.ModelAdmin): 
    fieldsets = [
    (None, {"fields": ("Form", "Authorized_Users", "Authorized_Groups")}),]
    def save_model(self, request, obj, form, change):
        if getattr(obj, 'user', None) is None:  
            obj.user = request.user
        obj.save()
    def get_queryset(self, request):
        qs = super(RestrictedFormAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)
    def has_change_permission(self, request, obj=None):
        if not obj:
            return True 
        return obj.user == request.user or request.user.is_superuser

admin.site.register(Restricted_Form, RestrictedFormAdmin)

Help will be greatly appreciated.

like image 738
S_alj Avatar asked Jun 11 '26 09:06

S_alj


1 Answers

You can try something like this:

class RestrictedFormAdmin(admin.ModelAdmin):
    def render_change_form(self, request, context, *args, **kwargs):
        context['adminform'].form.fields['Form'].queryset = Form.objects.filter(user=request.user)
        return super(RestrictedFormAdmin, self).render_change_form(request, context, args, kwargs)         
like image 104
Diego Puente Avatar answered Jun 13 '26 22:06

Diego Puente



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!