Question

That may seem obvious, but I cannot figure it out for a while. I have three models: Project, Question_Text, and Question. Question has ForeignKey to the Project and to the Question_Text. I can create and save Project, but when I'm creating Question_Text, I should also create a Question in my understanding, from one view. I tried to use Question.objects.create(), however, my dances around this seem fatal. I get the below error:

table project_question has no column named question_text_id

From DB point of view it's like this:

"question_text_id" integer NOT NULL REFERENCES "project_question_text" ("id")

My models:


class Project(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=40)
    audience_count = models.IntegerField(default=0)
    audience_ready = models.IntegerField(default=0)
    pub_date = models.DateTimeField("Date Created")

    def __unicode__(self):
        return self.title

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


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

My view:

def add_question(request, project_id):
    a = Project.objects.get(id=project_id)

    if request.method == "POST":
        f = QuestionTextForm(request.POST)
        if f.is_valid():
            c = f.save(commit=False)
            #          c.pub_date = timezone.now()
            q = Question.objects.create()
            q.question_text = c
            q.project = a
            q.save()
            c.save()

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

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

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


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

    #    args['question'] = q
    args['project'] = a
    args['form'] = f

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

And my form:

class QuestionTextForm(forms.ModelForm):

    class Meta:
        model = Question_Text
        fields = ('text_en',)

Any help is appreciated.

Was it helpful?

Solution

You are saving q before c. But as q has field (foreignkey) for c, c needs to be saved first. Django internally refers id of c to update the tables and rows appropriately.

So change your code to

    c = f.save(commit=False)
    #          c.pub_date = timezone.now()
    c.save() #save c

    #prepare object
    q = Question()
    q.question_text = c
    q.project = a
    q.user = request.user
    q.save()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top