django表单不使用默认主键

nzrxty8p  于 2021-06-24  发布在  Mysql
关注(0)|答案(0)|浏览(185)

我在答案表单中使用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,
                  })

谢谢您。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题