Django表单不使用默认主键

时间:2018-04-24 11:48:05

标签: mysql django django-models django-forms primary-key

我在答案表单中使用IntegerField来获取问题页面的ID。但是IntegerField没有获得id页面,它获得了这个页面的标题。我认为是因为主键是标题,但不是,我试图在问答模型中设置id = models.AutoField(primary_key=True),但情况是一样的。这是我的表单类:

class AddAnswerForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea)
    question = forms.IntegerField()

    def clean_question(self):
        question_id = self.cleaned_data['question']
        try:
            question = Question.objects.get(id=question_id)
        except Question.DoesNotExist:
            question = None
        return question

    def clean(self):
        pass

    def save(self):
        answer = Answer(**self.cleaned_data)
        answer.save()
        return answer

那是我的模特:

class Question(models.Model):
    title = models.CharField(default='', max_length=255)
    text = models.TextField(default='')
    added_at = models.DateTimeField(blank=True, auto_now_add=True)
    rating = models.IntegerField(default=0)
    author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='question_user')
    likes = models.ManyToManyField(User, related_name='question_like_user')

    def __str__(self):
        return self.title

    def get_url(self):
        return '/question/{}/'.format(self.id)


class Answer(models.Model):
    text = models.TextField(default='')
    added_at = models.DateField(blank=True, auto_now_add=True)
    question = models.ForeignKey(Question, on_delete=models.SET_NULL, null=True, related_name='answer_question')
    author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='answer_user')

    def __str__(self):
        return self.text

这就是我的观点:

def question(request, pk):
    try:
        q = Question.objects.get(id=pk)
    except Question.DoesNotExist:
        raise Http404
    a = Answer.objects.all()
    u = User.objects.all()
    if request.method == 'POST':
        form = AddAnswerForm(request.POST)
        if form.is_valid():
            _ = form.save()
            url = q.get_url()
            return HttpResponseRedirect(url)
    else:
        form = AddAnswerForm(initial={
            'question': q,
            'answer': a,
            'user': u,
        })
    return render(request, 'question.html',
                  {
                      'form': form,
                      'question': q,
                      'answer': a,
                      'user': u,
                  })

谢谢。

0 个答案:

没有答案