Django Admin Many To Many Subset
I'm trying to integrate in Django admin the next three related models: # models.py class Seminar(models.Model): title = models.CharField(max_length=128, unique=True) start_
Solution 1:
Well so, just before asking here, I did something similar to Django's auth.User
model by using different forms for add/change views. I hoped there was a better solution, obviously not.
So here is what I did:
# models.pyclassRegistration(models.Model):
# [...] - add form excludes it, should allow blank on events field
events = models.ManyToManyField('Event', blank=True, null=True)
# admin.pyclassRegistrationAdmin(admin.ModelAdmin):
change_form = RegistrationChangeForm
defget_form(self, request, obj=None, **kwargs):
defaults = {}
if obj isNone:
defaults.update(exclude=('events',))
else:
defaults.update(form=self.change_form)
defaults.update(kwargs)
returnsuper(RegistrationAdmin, self).get_form(request, obj, **defaults)
# forms.pyclassRegistrationChangeForm(forms.ModelForm):
classMeta:
model = Registration
exclude = ('seminar',)
def__init__(self, *args, **kwargs):
super(RegistrationChangeForm, self).__init__(*args, **kwargs)
self.fields['events'].choices = Event.objects.filter(seminar=kwargs.get('instance').seminar).values_list('pk','title')
So, when adding we simply ignore events (registration is saved with nulled events) and then, on change a list of events can be selected based on the previously defined seminar which is then ignored (since we can't reload the related events list).
Post a Comment for "Django Admin Many To Many Subset"