Django class based views - UpdateView with two model forms - one submit

PPiscuc picture PPiscuc · Aug 8, 2013 · Viewed 10.9k times · Source

I have a page with a list of users, and would like to be able to click a link to update their profile. When 'update' is clicked, I should be able to edit the username, first name, ... email, phone number, department etc, in a single page, using a single submit button. I accomplished this by using two forms, one for User, and one for the extra information. The ListView, DeleteView and CreateView work perfectly with these two forms, but not the UpdateView. I am not able to instantiate the two forms with initial data.

The question is: how do I instantiate the two forms with data? Overwrite self.object? get_form_kwargs? What would be the most elegant solution?

The UpdateView class is below. I am not looking for a 'copy-paste' solution, but maybe point me into the right direction.

Thanks.

Paul

The phone number, department is defined in a model named Employee.

class Employee(models.Model):
    user = models.OneToOneField(User)
    phone_number = models.CharField(max_length=13, null=True)
    department = models.CharField(max_length=100)

The template is:

{% 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 %}

The view class is:

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)
            # used to set the password, but no longer necesarry
            userdata.save()
            employeedata = form2.save(commit=False)
            employeedata.user = userdata
            employeedata.save()
            messages.success(self.request, 'Settings saved successfully')
            return HttpResponseRedirect(self.get_success_url())
        else:
            return self.render_to_response(
              self.get_context_data(form=form, form2=form2))

    def get_success_url(self):
        return reverse('client_list')

Answer

kdb picture kdb · Sep 4, 2013

You should be able to use the "instance" kwarg for the instantiation of the form from an existing model if that's what you need. Example:

context['form'] = self.form_class(self.request.GET, instance=request.user)