I have a page with a list of users, and you want to be able to click the link to update your profile. When clicked “update”, I should be able to edit the username, name, email address, phone number, department, etc. On one page using a single submit button. I did this using two forms: one for the User and one for additional information. ListView, DeleteView, and CreateView elements work fine with these two forms, but not with UpdateView. I cannot create an instance of two forms with source data.
The question arises: how do I create two forms with data? Overwrite self.object? get_form_kwargs? What would be the most elegant solution?
The following is the class of UpdateView. I'm not looking for a copy-paste solution, but I might point me in the right direction.
Thanks.
Floor
The phone number, department is defined in a model called Employee.
class Employee(models.Model): user = models.OneToOneField(User) phone_number = models.CharField(max_length=13, null=True) department = models.CharField(max_length=100)
Template:
{% extends "baseadmin.html" %} {% load crispy_forms_tags %} {% block content %} <h4>Edit a user</h4> <form action="" method="post" class="form-horizontal"> <legend>Edit a user</legend> {% crispy form %} {% crispy form2 %} <div class="form-actions"> <input type="submit" class="btn btn-primary" value="Save"> <a href="{% url 'client_list' %}" class="btn">Cancel</a> </div> </form> {% endblock content %}
Presentation Class:
class ClientUpdateView(UpdateView): model = User form_class = ClientsUserForm second_form_class = ClientsForm template_name = 'admin/client_update.html' def get_context_data(self, **kwargs): context = super(ClientUpdateView, self).get_context_data(**kwargs) context['active_client'] = True if 'form' not in context: context['form'] = self.form_class(self.request.GET) if 'form2' not in context: context['form2'] = self.second_form_class(self.request.GET) context['active_client'] = True return context def get(self, request, *args, **kwargs): super(ClientUpdateView, self).get(request, *args, **kwargs) form = self.form_class form2 = self.second_form_class return self.render_to_response(self.get_context_data( object=self.object, form=form, form2=form2)) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.form_class(request.POST) form2 = self.second_form_class(request.POST) if form.is_valid() and form2.is_valid(): userdata = form.save(commit=False)