我一直在研究我的Django项目。 我使用自定义表单(一个名为Form的类),我有一个名为 Restricted_Form 的类。此类的要点是管理员用户(“员工状态”用户“)具有限制哪些用户或组可以访问表单/提交填写表单的选项:
#....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")
“表格”本身有:
user = models.ForeignKey(User, blank=True, null=True)
#this is always the user who created it
我的问题是限制非超级用户管理员可以执行的操作。他们应该只能创建 Restricted_Form 对象,包括他们自己创建的表单。实际上,当他们创建Restricted_Form时,只有他们自己创建的“表单”应该在下拉菜单中显示为选择选项。 这是我现在的相关管理类:
#...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)
非常感谢帮助。
答案 0 :(得分:1)
您可以尝试这样的事情:
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)