我的 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
波斯汪
相关分类