title: Creating 2 objects and then creating a relation between the two using a single form
body: <p>Hi I have created a view which lets me create 2 different models that shares the same form. </p>
  
  <p>My 'member' model has a 'memberrole' field. What I would like is for when this form  is filled out correctly and after clicking submit, the field that is associated to the 'memberrole' model is created and then assigned to the 'member' model it shared the form with. </p>
  
  <p>I can't seem to get my head around how I should approach this task. I am relatively new to web development, would this be where the use of AJAX would help? </p>
  
  <p><strong>Models</strong></p>
  
  <pre><code>class MemberRole(models.Model,get_fields):
      name = models.CharField(max_length = 20)
  
      def __unicode__(self): 
          return self.name
  
  class Member(models.Model,get_fields):
      first_name = models.CharField(max_length = 20)
      role = models.ForeignKey(MemberRole, null = True, blank = True)
  </code></pre>
  
  <p><strong>Forms</strong></p>
  
  <pre><code>class MemberForm(forms.ModelForm):
      class Meta:
          model = Member
          exclude = ('role',)
  
  class MemberRoleForm(forms.ModelForm):
      class Meta:
          model = MemberRole
  </code></pre>
  
  <p><strong>snippet of URLS</strong></p>
  
  <pre><code>url(r'^members', ModelListView.as_view(model = Member,page_name = 'Members',edit_link = 'updatemember/'), name='member-list'),
  url(r'^addmember', 'inventory.views.add_member', name = 'member-add'),
  </code></pre>
  
  <p><strong>View fucntion</strong></p>
  
  <pre><code>def add_member(request):
  
  model_url = 'member-add'
  
  if request.method == "POST":
      rform = MemberRoleForm(request.POST, instance=MemberRole())
      mform = MemberForm(request.POST, instance=Member())
      if rform.is_valid() and mform.is_valid():
          new_role = rform.save()
          new_member = mform.save()
          return HttpResponseRedirect('members')
  else:
      rform = MemberRoleForm(instance=MemberRole())
      mform = MemberForm(instance=Member())
  return render_to_response('create_model.html', {'role_form': rform, 'member_form': mform, 'model_url': model_url,},context_instance=RequestContext(request))
  </code></pre>
  
  <p><strong>snippet of create_model.html</strong></p>
  
  <pre><code>&lt;form action="{% url model_url %}" method="POST"&gt;
    {% csrf_token %}
  
    {% if model_url == 'member-list' %}
  
      {% for field in member_form %}
      &lt;div class="fieldWrapper"&gt;
          {{ field.errors }}
          {{ field.label_tag }} {{ field }}
      &lt;/div&gt;
      {% endfor %}
      {% for field in role_form %}
      &lt;div class="fieldWrapper"&gt;
          {{ field.errors }}
          {{ field.label_tag }} {{ field }}
      &lt;/div&gt;
      {% endfor %}
  
    {% endif %}
       &lt;input id="save_contact" type="submit" value="Add"/&gt;
  &lt;/form&gt;
  </code></pre>