Django CreateView: set user before validation

风流意气都作罢 提交于 2019-12-06 09:52:45

You can set instance.creator in the get_form_kwargs method.

class SymbolCreateView(LoginRequiredMixin, generic.CreateView):
    form_class = SymbolCreateForm

    def get_form_kwargs(self):
        kwargs = super(SymbolCreateView, self).get_form_kwargs()
        if kwargs['instance'] is None:
            kwargs['instance'] = Symbol()
        kwargs['instance'].creator = self.request.user
        return kwargs

Checking if kwargs['instance'] is None means that the code works with both CreateView and UpdateView.

In my case, I wanted the request user to be part of the validation process. The solution proposed here was more suitable. It suggests using form_valid as follows

def form_valid(self, form):
  form.instance.author = self.request.user
  # ... do some validation here about the user for example
  if passed_validation:
    return super().form_valid(form)

  form.add_error(None, ValidationError({"author": "invalid author because ..."}))
  return super().form_invalid(form)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!