Django populate a form.ChoiceField field from a queryset and relate the choice back to the model object

后端 未结 2 1279
小鲜肉
小鲜肉 2021-02-05 20:48

I have a simple form:

class SubmissionQuickReplyForm(forms.Form):
    comment_text = forms.CharField(label=\'\', required=False, widget=forms.Textarea(attrs={\'r         


        
2条回答
  •  孤街浪徒
    2021-02-05 21:00

    You can use ModelChoiceField instead.

    choice = forms.ModelChoiceField(queryset=MyChoices.objects.all())
    

    And you can get by simply call cleaned_data like this.

    if request.method == "POST":
        form = SubmissionQuickReplyForm(request.POST)
        if form.is_valid():
            ch = form.cleaned_data.get('choice')
    

提交回复
热议问题