/ feedback / by / XXX / new处的ValueError无法分配“ <simplelazyobject:<user:=“” xxx =“” >>“:“ Model.user”必须是“ User”实例

时间:2018-06-22 15:10:31

标签: python django

我正在尝试构建此反馈应用程序,以使学生向他们的老师提供反馈。尝试创建反馈表单的实例时出现以下错误。请帮忙。谢谢。

错误:

ValueError at /feedback/by/XXX/new
Cannot assign "<SimpleLazyObject: <User: XXX>>": "Feedback.user" must be a "User" instance.

CreateView:

class CreateFeedback(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView):
    form_class = FeedbackForm
    model = models.Feedback

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)

表格:

class FeedbackForm(forms.ModelForm):
    class Meta:
        fields = ("teacher", "subject", "param1", "param2", "param3", "param4",
                    "param5", "param6", "param7", "param8", "param9", "param10")
        model = models.Feedback

urls.py中的路径:

path('by/<username>/new',views.CreateFeedback.as_view(),name='create'),

Models.py:

class Feedback(models.Model):
        user = models.ForeignKey(User, related_name = 'feedback', on_delete=models.CASCADE, blank=False, null=False)
        teacher = models.ForeignKey(Teacher, related_name = 'feedback', on_delete=models.CASCADE, blank=False, null=False)
        subject = models.ForeignKey(Subject, related_name = 'feedback', on_delete=models.CASCADE, blank=False, null=False)
        param1 = models.PositiveIntegerField(blank=False, null=False)
        param2 = models.PositiveIntegerField(blank=False, null=False)
        param3 = models.PositiveIntegerField(blank=False, null=False)
        param4 = models.PositiveIntegerField(blank=False, null=False)
        param5 = models.PositiveIntegerField(blank=False, null=False)
        param6 = models.PositiveIntegerField(blank=False, null=False)
        param7 = models.PositiveIntegerField(blank=False, null=False)
        param8 = models.PositiveIntegerField(blank=False, null=False)
        param9 = models.PositiveIntegerField(blank=False, null=False)
        param10 = models.PositiveIntegerField(blank=False, null=False)

        def get_absolute_url(self):
            return reverse(
                "feedback:detail",
                kwargs={"username": self.user.username, "pk": self.pk})

        def __str__(self):
            return (self.username + "->" + self.teacher)

        class Meta:
            ordering = ["teacher"]
            unique_together = ["user", "teacher", "subject"]

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

    def __str__(self):
        return self.username

1 个答案:

答案 0 :(得分:0)

更早的Django允许将整数分配给用户对象,但不知道从什么时候开始,但是它仅需要一个用户对象。

要解决您的问题

替换以下行

self.object.user = self.request.user

后跟一个

self.object.user = User.objects.get(id=self.request.user.id)