Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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')
like image 606
PPiscuc Avatar asked Aug 08 '13 09:08

PPiscuc


3 Answers

Try to quit the self.request.get on get_content_data forms constructors and use the "object" variable. With that get you reinitialize the constructor, more in this link.

My code:

 context['form'] = self.form_class(instance=self.object)
like image 60
Rafael GB Avatar answered Nov 10 '22 01:11

Rafael GB


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)
like image 31
kdb Avatar answered Nov 10 '22 02:11

kdb


Get rid of the method get, u don't need to superscribe it. And apply the following changes in place:

class ClientUpdateView(UpdateView):
       model = Employee # You can access the user by the profile, but not the 
       # oposit 
       form_class = ClientsForm
       second_form_class = ClientsUserForm
       template_name = 'admin/client_update.html'
      
       # def get(self, request, *args, **kwargs):
       # get rid off

       def get_context_data(self, **kwargs):
           kwargs['active_client'] = True
           if 'form' not in kwargs:
              kwargs['form'] = self.form_class(instance=self.get_object())
           if 'form2' not in kwargs:
              kwargst['form2'] = \ 
          self.second_form_class(instance=self.get_object().user)
          return super(ClientUpdateView, self).get_context_data(**kwargs)

       def post(self, request, *args, **kwargs): 
           ...
like image 30
Iaggo Capitanio Avatar answered Nov 10 '22 01:11

Iaggo Capitanio