一周来一直在努力解决这个问题.如何筛选模型以仅显示分配给特定登录用户的数据?我的观点.下面的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)

推荐答案

你的问题是:

choices = [('1', Result.decision.option1),
           ('2', Result.decision.option2)]

这里要做的是根据模型字段设置选项.你没有利用他们的价值观.它们的值与Result模型的特定实例有关.

通常,这个问题要求您知道Result模型的哪些实例将用于选项.我通常以kwargs的形式传递:

def __init__(self, *args, **kwargs):
         results = kwargs.pop('results')
         super().__init__(*args, **kwargs)

         # Now we're using a model INSTANCE, not the model itself
         # Also, you don't need to use the number for a key value. Makes
         # it a bit easier.
         choices = []
         for result in results.all():
             choices.append((result.decision.option1, result.decision.option1))
             choices.append((result.decision.option2, result.decision.option2))
         self.fields['vote'] = forms.ChoiceField(choices=choices, label="Choices", widget=forms.RadioSelect())

然后在视图中.py add get_form_kwargs初始化表单的kwargs:

def get_form_kwargs():
    kwargs = super().get_form_kwargs()
    kwargs.update({'results': Result.objects.filter(custom_user=self.request.user)})

    return kwargs

Python相关问答推荐

只需使用Python在图像中保留 colored颜色 范围区域

Flask主机持续 bootstrap 本地IP| Python

在Python中使用一行try

如何使用bs 4从元素中提取文本

基本链合同的地址是如何计算的?

Python中的函数中是否有充分的理由接受float而不接受int?

Odoo 14 hr. emergency.public内的二进制字段

如何检测背景有噪的图像中的正方形

Pandas 滚动最接近的价值

为什么这个带有List输入的简单numba函数这么慢

Julia CSV for Python中的等效性Pandas index_col参数

如何调整QscrollArea以正确显示内部正在变化的Qgridlayout?

SQLAlchemy Like ALL ORM analog

什么是合并两个embrame的最佳方法,其中一个有日期范围,另一个有日期没有任何共享列?

如何在Python中使用另一个数据框更改列值(列表)

旋转多边形而不改变内部空间关系

polars:有效的方法来应用函数过滤列的字符串

如何按row_id/row_number过滤数据帧

Python日志(log)模块如何在将消息发送到父日志(log)记录器之前向消息添加类实例变量

根据客户端是否正在传输响应来更改基于Flask的API的行为