You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django创建帖子时自动设置当前用户为作者的问题排查

解决Django自动分配帖子作者的问题

问题核心:移除表单中的author字段后,直接调用form.save()会触发数据库NOT NULL约束错误——因为表单不会提交author数据,而你之前用的initial={'author': request.user}仅用于渲染表单默认值,不会被包含在POST请求的表单数据里。

修复步骤:

1. 更新表单,移除author字段

修改PostForm的Meta类,只保留content字段(不需要让用户手动选择作者):

from django import forms
from publication.models import Userpublication

class PostForm(forms.ModelForm):
    content = forms.CharField(label='',widget=forms.Textarea(attrs={'class': 'content_toggle app-textarea',
                                                              'autofocus': 'true',  # 修正原代码的拼写错误:utofocus → autofocus
                                                              'maxlength': '250',
                                                              'placeholder': 'hello',
                                                              'required': True}))

    class Meta:
        model = Userpublication
        fields = ['content']  # 移除author字段
        labels = {
            'content': '',  # 修正原标签名错误:Content → content
        }

2. 修改视图,手动设置作者并保存

表单验证通过后,先以commit=False创建实例,手动赋值author后再保存到数据库:

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from .forms import PostForm
from publication.models import Userpublication

@login_required  # 新增:确保只有登录用户能创建帖子
def create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)  # 无需传initial,表单已无author字段
        
        if form.is_valid():
            post = form.save(commit=False)  # 创建实例但不立即写入数据库
            post.author = request.user  # 手动绑定当前登录用户为作者
            post.save()  # 保存完整实例到数据库
            return redirect('home')
    else:
        form = PostForm()  # GET请求无需initial
    post_lists = Userpublication.objects.all()
    context = {
        'form': form,
        'post_lists': post_lists,
    }
    return render(request, 'twippie/home.html', context)

关键说明:

  • commit=False的作用是生成模型实例但不提交到数据库,让你有机会补充表单未包含的字段数据。
  • 新增@login_required装饰器可以避免匿名用户访问该视图时,request.user为空导致的新错误。

内容的提问来源于stack exchange,提问作者Super DReik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 17:25:04