Django,获取ChoiceField表单的值

问题描述 投票:0回答:1

我有一个表单,其中包含数据库中项目的选择字段。 我的问题是如何获取 choicheField 的选定值?

表格.py

class list_data(forms.Form):
    message = forms.CharField(widget=forms.Textarea)

    def __init__(self, author, *args, **kwargs):
        super(list_data, self).__init__(*args, **kwargs)
        self.fields['List'] = forms.ChoiceField(
            choices=[(o.id, str(o)) for o in List.objects.filter(author=author)]
        )

views.py

def sms(request):
    form2  = list_data(author=request.user)

    if request.method == "POST":
        form2 = list_data(request.POST)
        if form2.is_valid():
            choice = form2.cleaned_data["List"]
            print(choice)

    else:
        return render(request, "data_list/sms.html", {"form2": form2})


    return render(request, "data_list/sms.html", {"form2": form2})

当我尝试按提交按钮时,它给我这个错误:

 int() argument must be a string, a bytes-like object or a number, not 'QueryDict'

所以我把

form2 = list_data(request.POST)
改为
form2 = list_data(author=request.user)
错误消失了,但没有打印任何其他内容。

感谢您的帮助

模型.py

class List(models.Model):
    item = models.CharField(max_length=100)
    content = models.TextField()
    site = models.CharField(max_length=11, choices=THE_SITE)
    content_list = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)


    def __str__(self):
        return self.item
python django forms django-forms
1个回答
3
投票

如果是 POST 请求,您将

request.POST
作为第一个参数传递,因此作为
author
,而不是作为数据。您可以将视图重写为:

def sms(request):
    if request.method == 'POST':
        form2 = list_data(request.user, data=request.POST)
        if form2.is_valid():
            choice = form2.cleaned_data["List"]
            print(choice)
    else:
        form2  = list_data(author=request.user)
    return render(request, "data_list/sms.html", {"form2": form2})

不过,我建议在此处使用

ModelChoiceField
[Django-doc],这将删除一些样板逻辑,然后您可以使用模型对象:

class ListDataForm(forms.Form):
    message = forms.CharField(widget=forms.Textarea)
    list = forms.ModelChoiceField(queryset=List.objects.none())

    def __init__(self, author, *args, **kwargs):
        super(list_data, self).__init__(*args, **kwargs)
        self.fields['list'].queryset = List.objects.filter(author=author)

请注意,根据 PEP-0008 风格指南,类应以 PerlCase 编写(因此

ListDataForm
,而不是
list_data
),并且属性应以 Snake_case 编写,因此
list
,而不是
List

© www.soinside.com 2019 - 2024. All rights reserved.