1

I have a model like :

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    type = models.ManyToManyField(Type, blank=True)

Here from admin I am adding MyModel.

What I want is if the type is not provided while saving then I want the type to be as default like Teacher

type Teacher has not been created. If the type is not provided I want to create the type and assign it if the type is not provided

varad
  • 7,309
  • 20
  • 60
  • 112

1 Answers1

2

According to documentation's example, you can override save_model like this:

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    def save_related(self, request, form, formsets, change):
        if not form.cleaned_data['type']:
            type, created = Type.objects.get_or_create(name="Teacher")
            form.cleaned_data['type'] = [type]
        form.save_m2m()
        for formset in formsets:
             self.save_formset(request, form, formset, change=change)
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • I tried this but type is not being added to obj. MyModel is being saved but type is not added to it.. – varad Sep 21 '15 at 07:59
  • Hi @aryan, I have updated the answer. Please check if it works for you :) – ruddra Sep 21 '15 at 10:50
  • Thank you it works and I have did it already.. but thank you for your effort.. I have also done with same process as yours – varad Sep 21 '15 at 11:37