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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.