如何在LIstview和ModelFormMixin的以下实现中获取当前登录的用户:
class ListMessages(ListView, ModelFormMixin):
model = Message
template_name = 'accounts/list_messages.html'
context_object_name = 'messages'
form_class = MessageHiddenUserForm
#success_url = reverse_lazy('accounts:list_messages', kwargs={'uname': })
def post(self, request, *args, **kwargs):
self.object = None
self.form = self.get_form(self.form_class)
if self.form.is_valid():
self.form.user_to = self.kwargs['uname']
self.form.user_from = request.user #this doesn't work
self.object = self.form.save()
return self.get(request, *args, **kwargs)
答案 0 :(得分:1)
问题不在于您从哪里获取用户,而是您将其分配到的位置。在表单上设置任意属性根本不做任何事情;您需要将其分配给form.save
的结果。
obj = self.form.save(commit=False)
obj.user_to = self.kwargs['uname']
obj.user_from = request.user
obj.save()
注意,您不能直接调用self.get()
;成功发布后,您必须始终重定向。
return redirect('accounts:list_messages', kwargs={...})
答案 1 :(得分:0)
方法" post"使用request.user.username获取当前登录用户。