﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
24787	Cannot assign a ForeignKey field with blank=True and null=False in Model.clean()	Suriya Subramanian	nobody	"Here's my model code

{{{
from django.db import models
from django.contrib.auth.models import User

class MyModel(models.Model):
    user = models.ForeignKey(User, blank=True, null=False)

    def clean(self):
        defaultuser = User.objects.first()
        if not defaultuser:
            raise ValueError('Need at least one user')
        self.user = defaultuser
        return super(MyModel, self).clean()
}}}

Here's my code where I create and initialize a `ModelForm`

{{{
from __future__ import print_function

import django
django.setup()

from myapp.models import MyModel
from django.forms.models import modelform_factory

MyForm = modelform_factory(MyModel, fields=('user', ))
myform = MyForm({})
print(myform.is_valid())
}}}

Here's the crash on running the above program:
{{{
Traceback (most recent call last):
  File ""a.py"", line 10, in <module>
    print myform.is_valid()
  File ""/home/vagrant/bookshelf.git/my-env/local/lib/python2.7/site-packages/django/forms/forms.py"", line 184, in is_valid
    return self.is_bound and not self.errors
  File ""/home/vagrant/bookshelf.git/my-env/local/lib/python2.7/site-packages/django/forms/forms.py"", line 176, in errors
    self.full_clean()
  File ""/home/vagrant/bookshelf.git/my-env/local/lib/python2.7/site-packages/django/forms/forms.py"", line 394, in full_clean
    self._post_clean()
  File ""/home/vagrant/bookshelf.git/my-env/local/lib/python2.7/site-packages/django/forms/models.py"", line 427, in _post_clean
    self.instance = construct_instance(self, self.instance, opts.fields, construct_instance_exclude)
  File ""/home/vagrant/bookshelf.git/my-env/local/lib/python2.7/site-packages/django/forms/models.py"", line 62, in construct_instance
    f.save_form_data(instance, cleaned_data[f.name])
  File ""/home/vagrant/bookshelf.git/my-env/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py"", line 874, in save_form_data
    setattr(instance, self.name, data)
  File ""/home/vagrant/bookshelf.git/my-env/local/lib/python2.7/site-packages/django/db/models/fields/related.py"", line 619, in __set__
    (instance._meta.object_name, self.field.name)
ValueError: Cannot assign None: ""MyModel.user"" does not allow null values.
}}}

What's the right way to support a `ForeignKey` with `blank=True` and `null=False`? Form validation does not even raise `ValidationError`. It simply crashes.

Had a conversation with @apollo13 on IRC who said that this is a bug to be reported."	New feature	closed	Forms	1.8	Normal	fixed			Accepted	0	0	0	0	0	0
