改变 Django 形式

我如何调整我的代码,以便用户不能为新帖子选择另一个用户。我想让登录用户自动添加为作者。


我尝试将 views.py 中的字段部分设置为内容字段,但它不起作用


models.py


class post(models.Model):

    author = models.ForeignKey(User, on_delete=models.CASCADE)

    content = models.CharField(max_length=140)


views.py


class CreatePostView(CreateView):


    model = post

    fields = '__all__'

    template_name = 'users/create.html'


我的表单.html


<form method="post">

    {% csrf_token %}

    {{ form.as_p }}

    <input type="submit" value="Login">

</form>


慕尼黑8549860
浏览 130回答 3
3回答

慕少森

class CreatePostView(CreateView):&nbsp; &nbsp; model = post&nbsp; &nbsp; template_name = 'users/create.html'&nbsp; &nbsp; fields = ['content']&nbsp; &nbsp; def form_valid(self, form):&nbsp; &nbsp; &nbsp; &nbsp; form.instance.author = self.request.user&nbsp; &nbsp; &nbsp; &nbsp; return super().form_valid(form)

人到中年有点甜

您需要做三件事:保护页面,使匿名用户无法访问它,使用LoginRequiredMixin从字段中删除用户提交表单后在提交的表单中输入当前用户,使用form_valid方法from django.views.generic.edit import CreateViewfrom django.contrib.auth.mixins import LoginRequiredMixinclass CreatePostView(LoginRequiredMixin, CreateView):&nbsp; &nbsp; model = Post&nbsp; &nbsp; fields = ["content"]&nbsp; &nbsp; template_name = "create.html"&nbsp; &nbsp; def form_valid(self, form):&nbsp; &nbsp; &nbsp; &nbsp; form.instance.user = self.request.user&nbsp; &nbsp; &nbsp; &nbsp; return super().form_valid(form)

ITMISS

request.user.username 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python