如何将登录用户链接到他创建的帖子?

时间:2020-02-25 21:06:49

标签: python django

我正在学习Django,并在django网站上制作了该教程。我以为我可以将用户链接到他创建的民意测验,但是我为此感到挣扎。登录并创建民意测验时,我看不到用户名。在数据库列author_id中,值为null。我将不胜感激。

这是我的代码

from django.db import models
from django.utils import timezone
import datetime
from django.contrib import auth
# Create your models here.

User = auth.get_user_model()

class Question(models.Model):
   question_text = models.CharField(max_length=200)
   author = models.ForeignKey(User, on_delete=models.CASCADE, null=False)

def __str__(self):
    return self.question_text

class Choice(models.Model):
   question = models.ForeignKey(Question, on_delete=models.CASCADE)
   choice_text = models.CharField(max_length=200)
   votes = models.IntegerField(default=0)
def __str__(self):
    return self.choice_text

class User(auth.models.User, auth.models.PermissionsMixin):

    def __str__(self):
        return "@{}".format(self.username)

forms.py:

class UserCreateForm(UserCreationForm):

    class Meta:
        fields = ('username', 'email', 'password1', 'password2')
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].label = 'Display Name'
        self.fields['email'].label = 'Email Address'

class CreatePollForm(forms.ModelForm):

    class Meta:
        model = Question
        fields = ('question_text',)

和views.py

class CreatePoll(LoginRequiredMixin, generic.CreateView):
    form_class = forms.CreatePollForm
    success_url = reverse_lazy('pollapp:index')
    template_name = 'polls/createPoll.html'

1 个答案:

答案 0 :(得分:1)

由于您的CreatePollForm仅分配了question_text字段,因此您需要在代码中分配authorCreateViewFormView,它以其form_valid()方法保存表单。因此,在您的CreateView中,您想覆盖该方法:

# in class CreatePoll
def form_valid(self, form):
    question = form.save(commit=False)  # fetch the new question, don't save
    question.author = self.request.user  # assign the user
    question.save()  # now save
    return super().form_valid(form)

目前尚不清楚如何以null的{​​{1}}值结束,而该值本应引发author_id。您确定您在当前状态下运行过IntegrityErrormakemigrations吗?