Django - OneToOneField 不断返回 None

我的 OneToOneField 不断返回 None。我尝试访问我的网站,以便表单可以自动将帖子的作者作为当前登录的人。我环顾四周,发现 OneToOneField 可以做到这一点。当我实际上在 User 模型中有用户时,它会一直返回 None 。地球上发生了什么?


Models.py: - 这是主要问题发生的地方


from django.db import models

from datetime import datetime

from django import forms

from django.forms import ModelForm

from django.contrib.auth.models import User

from django.conf import settings

from django.contrib.auth import get_user_model




class 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_title


class MainPostForm(ModelForm):

    class Meta:

        model = MainPost

        fields = ["post_title", "post_content", "post_author"]

        readonly_fields = "post_published"

Views.py - 重要的是底部的 create_request()

from django import forms

from django.contrib.auth.forms import UserCreationForm

from django.contrib.auth.models import User




class 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


慕村225694
浏览 71回答 1
1回答

波斯汪

尝试这个: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})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python