所以我有一个模型,其中包括:
class Place(models.Model): .... created_by = models.ForeignKey(User)
我的看法是这样的:
class PlaceFormView(CreateView): form_class = PlaceForm @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(PlaceFormView, self).dispatch(*args, **kwargs)
有没有办法让我访问request.user并将created_by设置为该用户?我浏览了所有文档,但似乎找不到任何提示。
如何覆盖form_valid保存表单?自己保存它,对它进行任何操作,然后进行重定向。
form_valid
class PlaceFormView(CreateView): form_class = PlaceForm @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(PlaceFormView, self).dispatch(*args, **kwargs) def form_valid(self, form): obj = form.save(commit=False) obj.created_by = self.request.user obj.save() return http.HttpResponseRedirect(self.get_success_url())