title: Django Forms - Many to Many relationships
body: <p>relatively new to Django and trying to piece together standard practice for dealing with M2M relationships in a form. I already have the model and db squared away. </p>
  
  <p>For this example, I've written an app in my project for Articles, and I'm attempting to add Categories. To keep it simple an Article has a title, body, timestamp (not included in form), and Categories. I prefer checkboxes to represent 1 or more categories that an Article can belong to. </p>
  
  <p>So far I have:</p>
  
  <h1>models.py</h1>
  
  <pre><code>class Category(models.Model):
      category = models.CharField(max_length=100)
  
      def __unicode__(self):
          return self.category
  
  
  class Article(models.Model):
      title = models.CharField(max_length=200)
      body = models.TextField()
      pub_date = models.DateTimeField(auto_now_add=True)
      category = models.ManyToManyField(Category)
  
      def __unicode__(self):
          return self.title
  </code></pre>
  
  <h1>views.py</h1>
  
  <pre><code>def article_index(request):
      return render_to_response('article_index.html', {'articles': Article.objects.all()})
  
  def article_detail(request, article_id=1):
      return render_to_response('article_detail.html', {'article': Article.objects.get(id=article_id)} )
  
  def article_create(request):
      if request.method == 'POST': # If the form has been submitted...
          form = ArticleForm(request.POST) # A form bound to the POST data
          if form.is_valid(): # All validation rules pass
              article = Article.objects.create(
                  title=form.cleaned_data['title'],
                  body=form.cleaned_data['body'],
                  category=form.cleaned_data['category']
              )
              return redirect('article_index') # Redirect after POST
      else:
          form = ArticleForm() # An unbound form
  
      return render(request, 'article_form.html', { 'form': form })
  </code></pre>
  
  <h1>forms.py</h1>
  
  <pre><code>class ArticleForm(forms.Form):
      title = forms.CharField(required=True)
      body = forms.CharField(required=True, widget=forms.Textarea)
      category = forms.MultipleChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple)
  </code></pre>
  
  <p>The two item's I'm currently stuck on are:</p>
  
  <p>1) in the view 'article_create', I'm not sure how to create the category(ies) as part of the Article object. In the shell, I had to create the Article with a call to save(), then add each category after that. Do I need to do something similar here, e.g. create the article then iterate through each category? Example code is appreciated.</p>
  
  <p>2) Haven't coded 'article_edit' yet, assuming it will be highly similar to create, but I'm not sure if or how I need to handle the logic for comparing previously selected categories to the current submission. Or, should I just delete all category entries for the article being edited, and re-enter them based on the current submission? That's probably the easiest. Again, sample code for this would help.</p>
  
  <p>Thanks!</p>