亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

關聯經過身份驗證的用戶以形成對象 Djano

關聯經過身份驗證的用戶以形成對象 Djano

米脂 2023-03-08 16:33:46
我在將用戶(外鍵)傳遞到提交的表單時遇到問題。這是模型的樣子: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模型部分。



查看完整回答
反對 回復 2023-03-08
  • 1 回答
  • 0 關注
  • 80 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號