title: Using an instance's fields to filter the choices of a manytomany selection in a Django admin view
body: <p>I have a Django model with a ManyToManyField.</p>
  
  <p>1) When adding a new instance of this model via admin view, I would like to not see the M2M field at all.</p>
  
  <p>2) When editing an existing instance I would like to be able to select multiple options for the M2M field, but display only a subset of the M2M options, depending on another field in the model. Because of the dependence on another field's actual value, I can't just use formfield_for_manytomany</p>
  
  <p>I can do both of the things using a custom ModelForm, but I can't reliably tell whether that form is being used to edit an existing model instance, or if it's being used to create a new instance. Even MyModel.objects.filter(pk=self.instance.pk).exists() in the custom ModelForm doesn't cut it. How can I accomplish this, or just tell whether the form is being displayed in an "add" or an "edit" context?</p>
  
  <p>EDIT: my relevant code is as follows:</p>
  
  <p>models.py</p>
  
  <pre><code>class LimitedClassForm(forms.ModelForm):
      def __init__(self, *args, **kwargs):
          super(LimitedClassForm, self).__init__(*args, **kwargs)
          if not self.instance._adding:
              # Edit form
              clas = self.instance
              sheets_in_course = Sheet.objects.filter(course__pk=clas.course.pk)
              self.Meta.exclude = ['course']
              widget = self.fields['active_sheets'].widget
              sheet_choices = []
              for sheet in sheets_in_course:
                  sheet_choices.append((sheet.id, sheet.name))
              widget.choices = sheet_choices
          else:
              # Add form
              self.Meta.exclude = ['active_sheets']
      class Meta:
          exclude = []
  </code></pre>
  
  <p>admin.py</p>
  
  <pre><code>class ClassAdmin(admin.ModelAdmin):
      formfield_overrides = {models.ManyToManyField: {
          'widget': CheckboxSelectMultiple}, }
      form = LimitedClassForm
  
  admin.site.register(Class, ClassAdmin)
  </code></pre>
  
  <p>models.py</p>
  
  <pre><code>class Course(models.Model):
      name = models.CharField(max_length=255)
  
  class Sheet(models.Model):
      name = models.CharField(max_length=255)
      course = models.ForeignKey(Course)
      file = models.FileField(upload_to=getSheetLocation)
  
  class Class(models.model):
      name = models.CharField(max_length=255)
      course = models.ForeignKey(Course)
      active_sheets = models.ManyToManyField(Sheet)
  </code></pre>
  
  <p>You can see that both Sheets and Classes have course fields. You shouldn't be able to put a sheet into active_sheets if the sheet's course doesn't match the class's course.</p>