第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Django - OneToOneField 不斷返回 None

Django - OneToOneField 不斷返回 None

慕村225694 2022-11-09 17:23:40
我的 OneToOneField 不斷返回 None。我嘗試訪問我的網(wǎng)站,以便表單可以自動(dòng)將帖子的作者作為當(dāng)前登錄的人。我環(huán)顧四周,發(fā)現(xiàn) OneToOneField 可以做到這一點(diǎn)。當(dāng)我實(shí)際上在 User 模型中有用戶時(shí),它會(huì)一直返回 None 。地球上發(fā)生了什么?Models.py: - 這是主要問題發(fā)生的地方from django.db import modelsfrom datetime import datetimefrom django import formsfrom django.forms import ModelFormfrom django.contrib.auth.models import Userfrom django.conf import settingsfrom django.contrib.auth import get_user_modelclass MainPost(models.Model):    post_author = models.OneToOneField(User, on_delete=models.CASCADE)    post_title = models.CharField(max_length=200)    post_content = models.TextField()    post_published = models.DateTimeField("date published", default=datetime.now())    def __str__(self):        return self.post_titleclass MainPostForm(ModelForm):    class Meta:        model = MainPost        fields = ["post_title", "post_content", "post_author"]        readonly_fields = "post_published"Views.py - 重要的是底部的 create_request()from django import formsfrom django.contrib.auth.forms import UserCreationFormfrom django.contrib.auth.models import Userclass NewUserForm(UserCreationForm):    email = forms.EmailField(required=True)    class Meta:        model = User        fields = ("username", "email", "password1", "password2")    def save(self, commit=True):        user = super(NewUserForm, self).save(commit=False)        user.email = self.cleaned_data["email"]        if commit:            user.save()        return user
查看完整描述

1 回答

?
波斯汪

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊

嘗試這個(gè):


def create_request(request):

    if request.method == 'POST':

        # create a form instance and populate it with data from the request:

        form = MainPostForm(request.POST)

        # check whether it's valid:

        if form.is_valid():

            main_post = form.save(commit=False)

            main_post.post_author = request.user

            main_post.save()

            return redirect("mymainapp:homepage")


    form = MainPostForm()

    return render(request, "trymysite/create.html", {"form":form})


查看完整回答
反對(duì) 回復(fù) 2022-11-09
  • 1 回答
  • 0 關(guān)注
  • 95 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)