django - 使用包含 RadioSelect 小部件的 ModelChoiceField 在 ModelForm 中的查询集中获取 request.user

标签 django django-forms django-views django-queryset modelform

我想向社区询问以下有关通过的问题request.userquerysetModelForm .我的 ModelForm是:

class goForm(ModelForm): 
    user_choice = goModelChoiceField(
            widget=forms.RadioSelect,
            queryset=Document.objects.all().filter(who_upload=request.user),
            empty_label=None,
            to_field_name='docfile',
            label = 'Please select'
            )            
    class Meta:
        model = go
        fields = ['user_choice']


class goModelChoiceField(forms.ModelChoiceField):
        def label_from_instance(self, obj):
            return  "'%s' uploaded on %s" % (obj.file_name, 
                obj.when_upload.date()) 

我找到的所有答案都是指通过 request.user__init__或填写 goForm在带有过滤选择的 View 中。然而,在我的情况下似乎没有任何工作,因为我已经对表单进行了子分类以返回特定的字符串并且我正在使用RadioSelect特别需要 queryset 的小部件作为一个论点(我不是 100% 确定)。那我怎么才能通过request.useruser_choice ?

最佳答案

model choice field docs展示如何在 __init__ 中设置查询集方法。

class goForm(ModelForm): 
    user_choice = goModelChoiceField(
        widget=forms.RadioSelect,
        queryset=None,
        empty_label=None,
        to_field_name='docfile',
        label = 'Please select'
        )            

    def __init__(self, user, *args, **kwargs):
        super(goForm, self).__init__(*args, **kwargs)
        self.fields['user_choice'].queryset = Document.objects.all().filter(who_upload=user)

    class Meta:
        model = go
        fields = ['user_choice']

请注意 __init__方法现在将用户作为参数,因此请记住在 View 中实例化表单的任何位置传递它。例如:
form = goForm(user=request.user, data=request.POST)

关于django - 使用包含 RadioSelect 小部件的 ModelChoiceField 在 ModelForm 中的查询集中获取 request.user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517980/

相关文章:

python - 添加额外的参数到serializer.data

django - 如何在模板中显示 Django 表单字段的值?

django - 适用于多对多字段的Django 1.2.1内联管理员

python - 检查一个范围内的任何日期是否在另一个范围之间

python - 在基于类的 View (CBV) 中引用当前用户

mysql - 内连接子查询 Django ORM 等效

python - 表单处理Django中的日期时间对象格式错误

python - Django 表单集中的只读字段

python - Django (1.2) 表单 : ManyToManyField Help Text

python - Django:如何在呈现 View 后更新模型?