Search code examples
djangodjango-modelsdjango-users

save user_id as a ForeignKey


I have a survey with a response model, which I like to link to an existing user. She should be able to view her past responses to a survey on a profile page. Well, that's the plan anyway. But I can't even link user to response.

(django==1.5, django-lazysignup)

The user is currently a ForeignKey in Response in order to get the linking

# models.p
from django.contrib.auth.models import User
class Response(models.Model):
    survey = models.ForeignKey(Survey)
    user = models.ForeignKey(User)
    ...

#views.py
@allow_lazy_user
def survey_detail(request, slug):
    ...
    if form.is_valid():
        response = form.save(commit=False)
        response.user = request.user
        response.save()
        ...

Error:

IntegrityError: null value in column "user_id" violates not-null constraint

The field user_id is included in table response. Due to south schemamigration I had to set a one-off value and choose an existing user_id.

Any thoughts?


Solution

  • It works using null=True, blank=True

    class Response(models.Model):
        survey = models.ForeignKey(Survey)
        user = models.ForeignKey(User, null=True, blank=True)
        ...