Django modelform not saving foreignkey

128 views
Skip to first unread message

Jonty Needham

unread,
Sep 28, 2016, 12:00:21 PM9/28/16
to django...@googlegroups.com
I have the following code which is supposed to create a MyConfig object. However, it doesn't as the app_model is always returned as None.

The idea is to choose from a select few contenttypes and then add a key, and the resulting config will trigger a bunch of services. However whenever I save the form, the contenttype stored in the app_model is always None, which is clearly undesirable.

This is in Django1.8

Here is the admin:

class ContentTypeModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "{}-{}".format(obj.app_label, obj.model)


class MyConfigForm(ModelForm):
    class Meta:
        model = models.MyConfig
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(MyConfigForm, self).__init__(*args, **kwargs)
        self.fields['app_model'].label = "App Name"

    app_model = ContentTypeModelChoiceField(
        ContentType.objects.filter(
            app_label__startswith='myApp',
            model="myModel",
        ),
        empty_label="Choose a model",
    )


class MyConfigAdmin(admin.ModelAdmin):
    model = models.MyConfig
    form =  MyConfigForm
    list_display = (<display fields>
    )
    search_fields = (<search fields>
    )

And here is the model itself:

class MyConfig(models.Model):

    app_model = models.ForeignKey(ContentType, null=True)
    ref_key = models.CharField(max_length=32, null=True)

Jonty Needham

unread,
Sep 28, 2016, 12:47:05 PM9/28/16
to django...@googlegroups.com
Ignore this. Field was in excluded_fields which I thought only stopped the display of fields, but actually stops the data from that field getting into the model.

Reply all
Reply to author
Forward
0 new messages