我在将用户(外键)传递到提交的表单时遇到问题。这是模型的样子:from django.db import modelsfrom person.models import UserProfilefrom django.urls import reversefrom django.conf import settingsfrom django.contrib.auth import get_user_modelfrom django.contrib.auth.models import Userfrom django.db.models import signalsUser = 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, 空)。显然我做错了什么。解决此问题的最佳方法是什么?
1 回答
30秒到达战场
TA贡献1828条经验 获得超6个赞
该字段的名称是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
模型部分。
添加回答
举报
0/150
提交
取消