I want to create my own form on the additional screen so that I can register almost the same number as I entered. I want to separate the form on the add screen and the change screen
In this example, multiple items with the same serial number but different branch numbers can be registered at one time.
Model
models.py
from django.db import models
class Job(models.Model):
serial_number = models.IntegerField("Serial number")
branch_number = models.IntegerField("Branch number")
deadline = models.DateField("The deadline")
Admin
admin.py
from django.contrib import admin
from django import forms
from .models import Job
#Form at the time of addition
class JobAdminAddForm(forms.ModelForm):
#Original form
number_of_jobs = forms.IntegerField(lable="Number of work")
class Meta:
model = Job
fields = ('serial_number', 'deadline')
#Form at the time of change
class JobAdminChangeForm(forms.ModelForm):
class Meta:
model = Job
fields = ('serial_number', 'branch_number', 'deadline')
class JobAdmin(admin.ModelAdmin):
list_display = ('id', 'serial_number', 'branch_number', 'deadline')
#Form switching
def get_form(self, request, obj=None, **kwargs):
if obj:#Specify JobAdminChangeForm as the form at the time of change
self.form = JobAdminChangeForm
else:#Specify JobAdminAddForm as the form when adding
self.form = JobAdminAddForm
return super().get_form(request, obj, **kwargs)
def save_model(self, request, obj, form, change):
#Save as is when changing
if change:
obj.save()
else:
for i in range(form.cleaned_data['number_of_jobs']):
obj.pk = None
obj.branch_number = i + 1
obj.save()
admin.site.register(Job, JobAdmin)
Override get_form to switch between forms when adding and when changing. By overriding save_model, the process at the time of saving can be rewritten. When changing, just save it as it is, and when adding, turn the for statement with the value of the original form and add the value to the branch number and save it. By substituting None for obj.pk, you can save each as separate data.
It seems that various things can be done by devising save_model. Please point out if there is anything.
Recommended Posts