简体   繁体   中英

Add field to django ModelForm that are in the model but not in the form

I have a django model and a ModelForm. The model has about 10 fields, but I only want to show a few with the ModelForm for the user. So I have something like this:

class Create_EventForm(ModelForm):
    class Meta:
        model = Event
        fields = ['event_name','event_datetime','event_venue','event_url','event_tags','event_zip','event_category','event_description']

However, I can't create an object based on this data, because there are still missing fields. When I receive the data via POST in my view I am doing one of these:

if request.user.is_authenticated:
        if request.POST:
            f = Create_EventForm(request.POST)
            if f.is_valid():
                ne = f.save()

What I want to do is right before the f.save() I want to do lookups based on existing data I have to pull in other data I need for the model and create the object. Any idea how this can be done?

Save the form with commit=False , edit the returned instance, then save it to the db.

if request.POST:
    f = Create_EventForm(request.POST)
    if f.is_valid():
        event = f.save(commit=False)
        event.other_value = lookup_value()
        event.save()

See the doc's on ModelForm 's save method for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM