在Django中为超级用户设置初始表单字段值

z18hc3ub  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(92)

我有写评论的形式,我想“作者”字段为默认为“管理员”,如果登录用户是超级用户。我还想隐藏超级用户的"作者"字段表单。
产品型号:

class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    author = models.CharField(max_length=20)
    text = models.TextField()
    publication_date = models.DateTimeField()

    def ___str___(self):
        return self.text

形式:

class CreateComment(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ["author", "text"]

    def __init__(self, *args, **kwargs):
        super(CreateComment, self).__init__(*args, **kwargs)

ChatGPT建议我在表单中添加以下内容:

if kwargs.get("user").is_superuser:
    self.fields["author"].widget = forms.HiddenInput()
    self.fields["author"].initial = "admin"

但我得到了这个错误:
工作环境:
申请方式:GET请求URL:http://127.0.0.1:8000/14/
Django版本:4.1.7 Python版本:3.9.7已安装的应用程序:已安装的中间件:请检查'django. middleware. security. SecurityMiddleware',' django. contrib. sessions. middleware. SessionMiddleware','django. middleware. common. CommonMiddleware',' django. middleware. csrf. CsrfViewMiddleware','django. contrib. auth. middleware. AuthenticationMiddleware',' django. contrib. messages. middleware. MessageMiddleware','django. middleware. clickjacking. XFrameOptionsMiddleware']
回溯(最近的呼叫最后一次):文件"C:\Users\Tomasz\anaconda3\lib\site-packages\django\core\handlers\exception.py",第56行,inner response = get_response(request)File "C:\Users\Tomasz\anaconda3\lib\site-packages\django\core\handlers\base.py",line 197,in_get_response response = wraped_callback(request,* callback_args,callback_kwargs)File "C:\Users\Tomasz\Desktop\myblog\mainapp\views.py",第41行,在article_view form = Comment()文件"C:\Users\Tomasz\Desktop\myblog\mainapp\forms.py",第23行,如果kwargs,则在init**中。get(" user"). is_superuser:
异常类型:AttributeError at/14/异常值:"NoneType"对象没有属性"is_superuser"
我很感激任何帮助,谢谢。

wlp8pajw

wlp8pajw1#

我建议修复你的Comment模型,而不是存储一个与User模型相关的字符串,并解析你想要的渲染(模板)信息。
但是,回答你的问题。基本上,您需要保存表单而不提交,这将创建一个模型示例。然后,手动设置其他字段:
views.py

def article_detail(request, pk):
    article = Article.objects.get(pk=pk)

    if request.method == "POST":
        form = CreateComment(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)
            comment.article = article
            comment.author = "admin" if request.user.is_superuser else form.cleaned_data["author"]
            comment.publication_date = datetime.now(timezone.utc)
            comment.save()
    else:
        form = CreateComment()

    context = {
        "article": article, 
        "form": form, 
        "comments": article.comment_set.all()
    }
    return render(request, "article/detail.html", context)

相关问题