Last active
April 30, 2022 23:06
-
-
Save daimon99/f3683b36b60858a2e5185d751f356ec9 to your computer and use it in GitHub Desktop.
Django admin different changeform in add / change。Django Admin新增与修改页面使用不同的Form。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@admin.register(m.Holiday) | |
class HolidayAdmin(admin.ModelAdmin): | |
list_display = ('id', 'day', 'category') | |
search_fields = ('day',) | |
list_filter = ('category',) | |
date_hierarchy = 'day' | |
def get_form(self, request, obj=None, change=False, **kwargs): | |
if not change: | |
kwargs['form'] = HolidayForm | |
# 如果 self.fields 为空,会再调 get_form() 获取 fields 值,这样造成重复调用,这时再传进来的的 change=False | |
self.fields = ['start_day', 'days', 'category'] | |
else: | |
self.fields = ['day', 'category'] | |
form = super().get_form(request, obj, change, **kwargs) | |
return form | |
def save_model(self, request, obj, form, change): | |
if change: | |
super().save_model(request, obj, form, change) | |
else: | |
# 如果在 form 中的 save 实现,还要考虑 m2m 的情况。麻烦。 | |
start_day = form.cleaned_data['start_day'] | |
days = form.cleaned_data['days'] | |
obj.category = form.cleaned_data['category'] | |
for i in range(days): | |
obj.id = None # 为 None 的时候会保存一条新记录 | |
obj.day = start_day + timedelta(days=i) | |
obj.save() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from datetime import timedelta | |
from django import forms | |
from .models import Holiday | |
class HolidayForm(forms.ModelForm): | |
start_day = forms.DateField() | |
days = forms.IntegerField(initial=1) | |
class Meta: | |
model = Holiday | |
fields = ['category', 'start_day', 'days'] | |
def clean(self): | |
days = self.cleaned_data['days'] | |
start_day = self.cleaned_data['start_day'] | |
for i in range(days): | |
day = start_day + timedelta(days=i) | |
if Holiday.objects.filter(day=day).exists(): | |
raise forms.ValidationError("包含的日期重复:%s" % (day.isoformat())) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Holiday(models.Model): | |
day = models.DateField(unique=True) | |
category = models.IntegerField(choices=HOLIDAY_CATEGORY, default=HOLIDAY) | |
def __str__(self): | |
return self.day.strftime('%Y%m%d') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment