Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Really, your only problem is that you've used a standard <code>Form</code> instead of a <code>ModelForm</code>. <code>Form</code> doesn't have a <code>save</code> method because it's not inherently tied to anything (i.e. it doesn't know what to save or where to save to).</p> <p>However, if you use a <code>ModelForm</code> you need to take care of all logic involved in creating a new studio in the form. This is actually better, though, because then you can just use the form and not worry about anything else: the form holds all the logic needed to properly save itself.</p> <pre><code>class FilmForm(forms.ModelForm): class Meta: model = Film # only need to define `new_studio`, other fields come automatically from model new_studio = forms.CharField(max_length=30, required=False, label = "New Studio Name") def __init__(self, *args, **kwargs): super(FilmForm, self).__init__(*args, **kwargs) # make `studio` not required, we'll check for one of `studio` or `new_studio` in the `clean` method self.fields['studio'].required = False def clean(self): studio = self.cleaned_data.get('studio') new_studio = self.cleaned_data.get('new_studio') if not studio and not new_studio: # neither was specified so raise an error to user raise forms.ValidationError('Must specify either Studio or New Studio!') elif not studio: # get/create `Studio` from `new_studio` and use it for `studio` field studio, created = Studio.objects.get_or_create(name=new_studio) self.cleaned_data['studio'] = studio return super(FilmForm, self).clean() </code></pre> <p>Then, in your view, all you need is:</p> <pre><code>if form.is_valid(): form.save() </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload