3 回答
TA贡献2019条经验 获得超9个赞
class CreatePostView(CreateView):
model = post
template_name = 'users/create.html'
fields = ['content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
TA贡献1895条经验 获得超7个赞
您需要做三件事:
保护页面,使匿名用户无法访问它,使用
LoginRequiredMixin
从字段中删除用户
提交表单后在提交的表单中输入当前用户,使用
form_valid
方法
from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
class CreatePostView(LoginRequiredMixin, CreateView):
model = Post
fields = ["content"]
template_name = "create.html"
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
添加回答
举报