猿问

关联经过身份验证的用户以形成对象 Djano

我在将用户(外键)传递到提交的表单时遇到问题。这是模型的样子:


from django.db import models

from person.models import UserProfile

from django.urls import reverse

from django.conf import settings

from django.contrib.auth import get_user_model

from django.contrib.auth.models import User

from django.db.models import signals



User = get_user_model()

# Create your models here.



class UserPost(models.Model, Activity):

    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='userpostauthor')

    content = models.TextField(max_length=2000, blank=True, null=True)

    postvideo = models.FileField(upload_to='UserPost/postvideo', blank=True, null=True)

    postPicture = models.FileField(upload_to='UserPost/postpicture', blank=True, null=True)

    created_at = models.DateTimeField(auto_now_add=True)

这是我的 views.py 形式:


class TimelineView(CreateView):

    fields= ['content', 'postvideo', 'postPicture']

    model = UserPost

    success_url = reverse_lazy('timeline_feed')

    template_name = 'main/timeline.html'



    def form_valid(self, form):

        form.instance.user = self.request.user


        return super(TimelineView, self).form_valid(form)


    def get_context_data(self, form=None):

        context = super(TimelineView, self).get_context_data()

当我尝试提交表单时会出现此错误:


“author_id”列中 /timeline/ 空值处的 IntegrityError 违反了非空约束详细信息:失败行包含 (20, , , , 2020-07-14 20:43:53.631628+00, null)。请求方法:POST 请求 URL: http ://127.0.0.1:8000/timeline/ Django 版本:2.2.12 异常类型:IntegrityError 异常值:“author_id”列中的空值违反了非空约束 详细信息:失败行包含 ( 20, , , , 2020-07-14 20:43:53.631628+00, 空)。


显然我做错了什么。解决此问题的最佳方法是什么?


米脂
浏览 51回答 1
1回答

30秒到达战场

该字段的名称是author,而不是user,因此您可以将其设置为:class TimelineView(CreateView):    fields= ['content', 'postvideo', 'postPicture']    model = UserPost    success_url = reverse_lazy('timeline_feed')    template_name = 'main/timeline.html'        def form_valid(self, form):        form.instance.author = self.request.user        return super().form_valid(form)注意:通常使用settings.AUTH_USER_MODEL[Django-doc]来引用用户模型比直接使用User模型 [Django-doc]更好。有关详细信息,您可以参阅文档的引用User模型部分。
随时随地看视频慕课网APP

相关分类

Python
我要回答