目标是,只有当他输入的日期在DateRange模型的日期范围内(从start_date到end_date)并且字段enable为True时,用户才能保存Marking模型。
models.py:
class DateRange(models.Model):
class Meta:
ordering = ['-first_date']
start_date = models.DateField(blank=False, null=True, verbose_name='Start Date')
end_date = models.DateField(blank=False, null=True, verbose_name='End Date')
enable = models.BooleanField(default=False, verbose_name='Enable')
def __str__(self):
return '{} to {} is {}'.format(self.first_date, self.end_date, self.enable)
class Marking(models.Model):
class Meta:
ordering = ['-first_date']
date = models.DateField(blank=False, null=True, verbose_name='Date')
order = models.BooleanField(default=False, verbose_name='Order')
def __str__(self):
return '{} / {}'.format(self.date, self.order)
forms.py
class DateRangeForm(forms.ModelForm):
class Meta:
model = DateRange
fields = [
'start_date',
'end_date',
'enable',
]
class MarkingForm(forms.ModelForm):
class Meta:
model = Marking
fields = [
'date',
'order',
]
views.py
def add_marking(request):
form = MarkingForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return HttpResponseRedirect(reverse("marking_info"))
context = {"form": form}
return render(request, 'add_marking.html', context)
我尝试了几种选择,但没有一个起作用。有人可以在正确的道路上帮助我吗?谢谢!
答案 0 :(得分:1)
如何在模型中放置干净的方法 例: models.py
class Marking(models.Model):
date = models.DateField(blank=False, null=True, verbose_name='Date')
order = models.BooleanField(default=False, verbose_name='Order')
def clean(self):
qs = DateRange.objects.filter(start_date__gte = self.date, end_date__lte = self.date, enable = True)
if not qs:
raise ValidationError('Measurement is outside the run')