我正在使用Django管理员编写保留程序。当所有房间更改的总夜晚数大于预订的总夜晚数时,程序将警告用户(通过Django messages)。因此,如果预订了7个晚上,并且用户将客人进入“ A”房间4个晚上,将“ B”房间4个晚上(总共8个晚上)输入,则用户将看到警告。警告而不是简单的表格错误的原因是,一个团队每晚可以有多个房间,这可能导致上述情况发生。
该代码有效(下面是相关部分)。
warn_if_rc_nights_gt_reservation_nights()
包含警告用户的逻辑,它对表单实例(仅在呈现表单时)或原始请求进行操作。POST变量(在表单被保存/发布时)以便计算整晚的房间变更和预订情况。
我可以使用表单实例来计算总夜晚数,但是我对原始POST变量有疑问,因为它更容易出错(POST变量还不是clean()
)并且不类似Django。我宁愿使用内置的类方法或函数来完成此操作。
我试图做到这一点:
reservations.models
class Room(models.Model):
room_number = models.CharField(max_length=16)
class Reservation(models.Model):
# Guest is in guest.models
guest = models.ForeignKey(Guest, on_delete=models.CASCADE)
check_in_date = models.DateField()
check_out_date = models.DateField()
class RoomChange(models.Model):
reservation = models.ForeignKey(Reservation on_delete=models.CASCADE)
room = models.ForeignKey(Room on_delete=models.CASCADE)
day_in = models.DateField()
day_out = models.DateField()
reservations.admin
@admin.register(Reservation)
class ReservationAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
# Uses a form factory to capture the request object.
self.form = _reservation_form_factory(request)
return super().get_form(request, obj, **kwargs)
@admin.register(Room)
class RoomAdmin(admin.ModelAdmin):
pass
@admin.register(RoomChange)
class RoomChangeAdmin(admin.ModelAdmin):
pass
reservations.forms
def _reservation_form_factory(request):
class ReservationAdminForm(forms.ModelForm):
class Meta:
exclude = []
model = Reservation
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Warn the user if total room change nights > reservation total nights
warn_if_rc_nights_gt_reservation_nights(request.POST, self.instance)
return ReservationAdminForm
所以最终我要求一种更简单,更不易出错的方式来完成此任务。