我正在创建一个投票应用程序,它使用管理面板(以及django-guardian),其中模型之间的相关foreignkey链是:
Vote =>
Choice (the choice being voted on) =>
Survey (the survey containing the choice) =>
User (the creator of the survey)
所需行为:- 当修改现有的调查投票时,管理员应该只显示来自该特定调查的选择。
- 添加新投票时,管理员应该以格式显示他们创建的所有调查中的所有选择"选择。choice_text (survey.question)"。
下面的代码几乎把我带到我需要的地方,除了一些事情(按对我的重要性排序):
- 显然,temp_creator需要调用对象的所有者调查,即当前登录的用户(request.user?)。
- 当编辑个人投票,我希望选择列表仅限于
- 添加新的通过管理面板投票,我希望所有的选择是可见的,但我喜欢追加调查。问题,这样用户就能分辨出来调查,如果调查共享相同的choice_text。
下面是我的代码:
# admin.py
class VoteForm(forms.ModelForm):
temp_creator = User.objects.get(pk=2)
surveys_owned = Survey.objects.filter(creator=temp_creator)
choice = forms.ModelChoiceField(queryset=Choice.objects.filter(survey__in=surveys_owned))
class Meta:
model = Vote
class VoteAdmin(GuardedModelAdmin):
fieldsets = [
('Required fields', {'fields':['voter_name','choice','rank']}),
]
#these lines are for how it's displayed in the admin panel
list_display = ('voter_name','user_name','choice','rank','date_modified','date_created')
list_filter = ['choice','rank','date_modified']
search_fields = ['choice','voter_name','user_name']
form = VoteForm
def queryset(self, request):
if request.user.is_superuser:
return super(VoteAdmin, self).queryset(request)
return get_objects_for_user(user=request.user, perms=['add_vote', 'change_vote', 'delete_vote'], klass=Vote, any_perm=True)
def save_model(self, request, obj, form, change):
"""When creating a new object, set the creator field.
"""
if not change:
obj.user_name = request.user
obj.save()
嗯,我能够部分地回答我的问题——通过在我的VoteAdmin类中包含这个方便的函数,并完全放弃VoteForm,问题1得到了解决:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "choice":
surveys_owned = Survey.objects.filter(creator=request.user)
kwargs["queryset"] = Choice.objects.filter(survey=surveys_owned)
return super(VoteAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
我还在写第二和第三期。我会在这里张贴决议,除非有人在我之前得到。
编辑:最终通过实现嵌套内联来回避这个问题。无论如何,如果能得到这个问题的答案就太好了,为了子孙后代。