我的 OneToOneField 不断返回 None。我尝试访问我的网站,以便表单可以自动将帖子的作者作为当前登录的人。我环顾四周,发现 OneToOneField 可以做到这一点。当我实际上在 User 模型中有用户时,它会一直返回 None 。地球上发生了什么?Models.py: - 这是主要问题发生的地方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贡献1811条经验 获得超4个赞
尝试这个:
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})
添加回答
举报
0/150
提交
取消