且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用createview和modelform在django中自动将登录用户设置为作者

更新时间:2023-12-04 09:17:04

使用 commit保存表单= False ,在对象上设置用户,然后保存对象。在 form_valid 方法内,您可以使用 self.request.user 访问该用户。您应该分配用户实例,而不是像当前代码那样分配用户名。

Save the form with commit=False, set the user on the object, then save the object. Inside the form_valid method, you can access the user with self.request.user. You should assign the user instance, not the username as your code currently does.

obj = form.save(commit=False)
obj.author = self.request.user
...
obj.save

还应该将视图限制为登录用户。您可以为此使用 LoginRequiredMixin

You should also restrict the view to logged in users. You can use the LoginRequiredMixin for this.

from django.contrib.auth.mixins import LoginRequiredMixin

class CreateArticle(LoginRequiredMixin, CreateView):