[Django]-Django form not saving with ModelChoiceField – ForeignKey

5👍

https://docs.djangoproject.com/en/stable/ref/forms/fields/#django.forms.ModelChoiceField.queryset

The queryset attribute should be a QuerySet. values_list returns a list.

You should just define the __str__ method of your Action model and you won’t have to redefine the action field in the form.

If it is set and you want to use another label, you can subclass ModelChoiceField.

The __str__ (__unicode__ on Python 2) method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object, and should return a string suitable for representing it. For example:

from django.forms import ModelChoiceField

class MyModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id

So, in your case, either set the __str__ method of Action model, and remove the action = forms.ModelChoiceField(...) line in your form:

class Action(models.Model):
    def __str__(self):
        return self.name

class SetForm(ModelForm):

    class Meta:
        model = Set
        fields = ['settitle', 'setdescrip', 'action', 'actorder']

Or either define a custom ModelChoiceField:

class MyModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.name

class SetForm(ModelForm):

    class Meta:
        model = Set
        fields = ['settitle', 'setdescrip', 'action', 'actorder']

    action = MyModelChoiceField(Action.objects.all())

Leave a comment