Note that there are some explanatory texts on larger screens.

plurals
  1. POSave new foreign key with django form
    primarykey
    data
    text
    <p>I have two models:</p> <pre><code>class Studio(models.Model): name = models.CharField("Studio", max_length=30, unique=True) class Film(models.Model): studio = models.ForeignKey(Studio, verbose_name="Studio") name = models.CharField("Film Name", max_length=30, unique=True) </code></pre> <p>I have a Film form that allows the user to either select a preexisting Studio, or type in a new one:</p> <pre><code>class FilmForm(forms.Form): studio = forms.ModelChoiceField(Studio.objects, required=False) new_studio = forms.CharField(max_length=30, required=False, label = "New Studio Name") name = forms.CharField(max_length=30, label = "Film Name") </code></pre> <p>There's validation to assure that the new_studio name doesn't already exist. If the user enters a new_studio, I want to save the studio and then save the new Film. </p> <pre><code>form = FilmForm(request.POST) if form.is_valid(): # All validation rules pass std = Studio(name = form.cleaned_data['new_studio']) std.save() </code></pre> <p>But then how do I save the Film instance subject to the brand new studio id? I've seen <a href="https://stackoverflow.com/questions/3953206/django-foreign-key-save">this question</a>, but what if I have many more fields in the Film model and Film Form? If I use the linked answer, I would have to enter each field:</p> <pre><code>studio = Studio.objects.get(name=request.POST['new_studio']) newFilm=Film(name=form.name, studio=studio, field_one = form.field_one, field_two = form.field_two, etc.) </code></pre> <p>What is the correct way to implement this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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