Question

I'm quite new to django, and I cannot understand why I get this error: project_question_text.question_id may not be NULL I have models which are interconnected together and a view:

class Question_Text(models.Model):
    text_en = models.CharField(max_length=60, blank=True)


class Question(models.Model):
    user = models.ForeignKey(User)
    question_text = models.ForeignKey(Question_Text)
    viewed = models.BooleanField(default=False)
    def __unicode__(self):
        return self.question_text

And view:

def add_question(request, project_id):
    a = Project.objects.get(id=project_id)
    if request.method == "POST":
        f = QuestionForm(request.POST)
        if f.is_valid():
            c = f.save(commit=False)
            c.project = a
            c.save()

            messages.success(request, "Your question was added")

            return HttpResponseRedirect('/projects/get/%s' % project_id)

    else:
        f = QuestionForm()

    args = {}
    args.update(csrf(request))

    args['project'] = a
    args['form'] = f

    return render_to_response('project/add_question.html', args)

May someone advice, please?

Was it helpful?

Solution

The error message seems to indicate that there's a question_id column in your project_question_text table, however, the Question_Text model doesn't contain any ForeignKey to Question. My guess is that you used to have a field like question = models.ForeignKey(Question) in your Question_Text model and at some point you changed the model definition. Your database table still reflects the old schema while your models don't.

The easiest solution would be to remove any tables you have changed and run syncdb again. Another solution would be to use migrations (i.e. South).

A slightly off-topic side note, standard Python code style suggests using CamelCase without underscores for class names, which means a slightly better and more standard name for your Question_Text model would be QuestionText.

OTHER TIPS

Are you sure if your initializing the new object on the else condition with the request params?

def add_question(request, project_id):
a = Project.objects.get(id=project_id)
if request.method == "POST":
f = QuestionForm(request.POST)
if f.is_valid():
    c = f.save(commit=False)
    c.project = a
    c.save()

    messages.success(request, "Your question was added")

    return HttpResponseRedirect('/projects/get/%s' % project_id)

else:
    f = QuestionForm(request.POST) #Add request params to initialization 

args = {}
args.update(csrf(request))

args['project'] = a
args['form'] = f

return render_to_response('project/add_question.html', args)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top