Frage

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?

War es hilfreich?

Lösung 2

It works using null=True, blank=True

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

Andere Tipps

The code you have looks good. The first thing I'd do to troubleshoot is inspect the User object right before you save it. print type(request.user), request.user. You could also inspect your Response model object to be sure it's what you expect. That'll indicate if you need to examine the form code or the decorator.

I'm not sure what you mean by "setting a one-off value" for South migration. South won't have anything to do with this. Are you talking about a hack with a fixed user_id to get the form to save? That's not right.

As you say in your own answer, setting null=True, blank=True on the user FK field will work, but in effect that means Responses can be submitted from "no one". Doing that seems like fixing a symptom.

Are you using django-lazysignup ("django-lazyuser" doesn't appear to be a thing)? Here's a potential pitfall. In short, that package creates temporary users that can hit a convert/ URL to choose a username and password to become official Users. Because not everyone will do that, there's a management command to clear out unconverted lazy users. That command will delete the LazyUser model object and the real User model object. By default, Django will cascade delete related objects, e.g. your Response object. To prevent Responses being silently deleted if they are associated with uncoverted lazy users, set the cascade property on the ForeignKey (docs). Something like user = models.ForeignKey(User, on_delete=models.PROTECT) and make sure the ProtectedError is safely handled. This only matters if you use that cleanup management command, but better safe than sorry and the next person to maintain the code might run cleanup because who doesn't like cleaning up.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top