1๐
I figured it out by looking at how CreateView
works.
The incoming request is processed by the post()
method of ProcessFormView
, which calls get_form_class()
and get_form()
. This latter method deals with a POST request, so the code of get_form_kwargs()
in FormMixin adds to the keywords dictionary the submitted data.
Now the form is bound (that is, it contains user supplied data or files) and the post()
method now tests the result of is_valid() and acts accordingly calling either form_valid() or form_invalid().
The FormMixin class puts the result of form.save()
into self.object
. The form.save()
method for modelforms is defined by BaseModelForm
and basically saves the instance of the Django model connected with the modelform, that is implements the actual creation at the base of the CreateView
form view. As form.save()
returns the object saved to the database, it makes sense to store it in self.object
and pass it to the template.
Hence,
class UserCreate(generic.CreateView):
model = User
template_name = 'crm2/create_user.html'
fields = ['email', 'username', 'namespaces']
success_url = reverse_lazy('crm2:userCreate')
def get_form(self, form_class):
form = super(UserCreate, self).get_form(form_class)
return form
def form_valid(self, form):
self.object = create_user(self.request.POST['username'],
self.request.POST['email'], str(uuid4()),
self.request.POST['namespaces'])
reset_link = get_reset_link(self.object)
send_mail_set_password(self.object, reset_link)
return HttpResponseRedirect(self.get_success_url())