Note that there are some explanatory texts on larger screens.

plurals
  1. POCatching validation errors in django forms
    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 (with help from an <a href="https://stackoverflow.com/questions/8996451/save-new-foreign-key-with-django-form">earlier question</a>:</p> <pre><code>class FilmForm(forms.ModelForm): required_css_class = 'required' studio = forms.ModelChoiceField(Studio.objects, required=False, widget = SelectWithPlus) new_studio = forms.CharField(max_length=30, required=False, label = "New Studio Name", widget = DeSelectWithX(attrs={'class' : 'hidden_studio_field'})) def __init__(self, *args, **kwargs): super(FilmForm, self).__init__(*args,**kwargs) self.fields['studio'].required = False def clean(self): cleaned_data = self.cleaned_data studio = cleaned_data.get('studio') new_studio = cleaned_data.get('new_studio') if not studio and not new_studio: raise forms.ValidationError("Must specify either Studio or New Studio!") elif not studio: studio, created = Studio.objects.get_or_create(name = new_studio) self.cleaned_data['studio'] = studio return super(FilmForm,self).clean() class Meta: model = Film </code></pre> <p>Now, my first issue is that when both studio and new_studio are missing <strong>I get a django ValueError: Cannot assign None: "Film.studio" does not allow null values error.</strong> I thought I was capturing all the errors, thus django should never get so far as to realize Film.studio is empty. </p> <p>A second issue is an order of operations. <strong>What if I want to only save the new_studio after I'm sure the rest of the FilmForm is valid (thus preventing a bunch of studio names getting saved before full Film entries go through as well)?</strong> Am I in the clear or do I risk premature saving because new_studio's are saved in the form's cleaning?</p> <p><strong>Edit: Added <a href="http://pastebin.com/TTZWbMb4" rel="nofollow noreferrer">Traceback</a> and edited validation if-statements</strong></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