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

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


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')


For ChoiceField you can use

    choice = forms.ChoiceField(choices=[    (choice.pk, choice) for choice in MyChoices.objects.all()])