Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow null in foreign key to user. Django

I have this model

class Vacancy(models.Model):
    user = models.ForeignKey(User, null=True, blank=True, default = None)
    name = models.CharField(max_length=64)

When in admin i try to creat a vacancy without a user. And it throws an error " club_vacancy.user_id may not be NULL". Am i doing something wrong?

like image 649
barin Avatar asked Nov 28 '09 15:11

barin


People also ask

How do I allow null in ForeignKey Django?

Thus, if you want to make a field optional, use either default=SOMETHING, blank=True, null=False or blank=True, null=True . Another exception is the string-like field, such as CharField . It's suggested that use the blank=True alone, leaving null=False behind.

How do I allow null values in Django?

So, if you want to save blank field you need to allow it on Django and Database level. blank=True - will allow empty field in admin panel null=True - will allow saving NULL to the database column.

What does ForeignKey mean in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

What is null false in Django?

null. If True , Django will store empty values as NULL in the database. Default is False .


2 Answers

club_vacancy.user_id may not be NULL

Looks very much like an error from your database, rather than from Django.

It seems most likely that you added null=True after running manage.py syncdb. You'll need to modify your database schema to allow null values in that column.

like image 103
Ben James Avatar answered Oct 18 '22 01:10

Ben James


Aside from South, another option is to use django evolution for schema changes.

http://code.google.com/p/django-evolution/

Install it before making db changes. Then run

python manage.py evolve --hint --execute

Make sure that if you add a new field, you allow nulls (null=True) or else evolve will give you an error message.

like image 24
dannyroa Avatar answered Oct 18 '22 00:10

dannyroa