一周来一直在努力解决这个问题.如何筛选模型以仅显示分配给特定登录用户的数据?我的观点.下面的py代码不起作用——它不能告诉表单.py它需要做什么来实现这一点.我发现错误"ForwardManyToneDescriptor"对象没有属性"option1".
它确实能在模板中有效过滤——但我需要使用RadioSelect小部件(在形式.py中定义)来显示特定登录用户必须 Select 的特定选项(我认为我不能——或者应该——在模板中编码).
意见.py
class VoteView(LoginRequiredMixin, CreateView):
model = Result
form_class = VotingForm
template_name = 'users/vote_form.html'
*Attempt #1:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Result'] = Result.objects.all()
context['user_specific'] =
Result.objects.filter
(custom_user=self.request.user)
return context
*Attempt #2:
def get_initial(self):
initial = super().get_initial()
initial.update({'custom_user': self.request.user})
return initial
形式.py
class VotingForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
choices = [('1', Result.decision.option1),
('2', Result.decision.option2)]
self.fields['vote'] = forms.ChoiceField(choices=choices, label="Choices", widget=forms.RadioSelect())
class Meta:
model = Result
fields = ['decision', 'vote']
模型.py(如果需要)
class Result(models.Model):
custom_user = models.ForeignKey(CustomUser)
decision = models.ForeignKey(Decision) * Decision
contains
decisions and
their choices
(like 'option1', 'option2')
vote = models.CharField()
vote_eligible = models.BooleanField(default=False)