Python 将经过身份验证的用户关联到窗体对象Djano
我无法将用户(外键)传递到提交的表单中。 以下是模型的外观:Python 将经过身份验证的用户关联到窗体对象Djano,python,django,django-models,django-forms,django-views,Python,Django,Django Models,Django Forms,Django Views,我无法将用户(外键)传递到提交的表单中。 以下是模型的外观: 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 U
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/null值处的IntegrityError违反
非空约束详细信息:失败的行包含(20,
2020-07-14 20:43:53.631628+00,空)。请求方式:POST请求
URL:Django版本:2.2.12异常
类型:IntegrityError异常值:列中的null值
“author_id”违反了非空约束详细信息:失败的行包含
(20,2020-07-1420:43:53.631628+00,空)
显然我做错了什么。解决此问题的最佳方法是什么?该字段的名称是
作者
,而不是用户
,因此您可以将其设置为:
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)
类时间线视图(CreateView):
字段=['content'、'postvideo'、'postPicture']
model=UserPost
success\u url=reverse\u lazy('timeline\u feed'))
模板名称='main/timeline.html'
def表单_有效(自身、表单):
form.instance.author=self.request.user
return super().form\u有效(form)
注意:通常最好使用来引用用户模型,而不是直接使用。有关更多信息,请参见
它应该是
form.instance.author=self.request.user
。现在只需创建一个不映射到字段的Django属性。