我在將用戶(外鍵)傳遞到提交的表單時遇到問題。這是模型的樣子: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()當我嘗試提交表單時會出現(xiàn)此錯誤:“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秒到達戰(zhàn)場
TA貢獻1828條經(jīng)驗 獲得超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]更好。有關(guān)詳細信息,您可以參閱文檔的引用User
模型部分。
添加回答
舉報
0/150
提交
取消