gpt4 book ai didi

python - 验证 CreateView 表单中日期时间输入的唯一性

转载 作者:行者123 更新时间:2023-12-04 17:42:23 27 4
gpt4 key购买 nike

我有这个模型,我需要的是唯一的时间,因为它是一个预订,所以当我创建一个新的预订时,我如何检查那个时间是否已经被选择。

模型.py

class Reserva(models.Model):
horario = models.DateTimeField(auto_now_add=False, auto_now=False)
cancha = models.ForeignKey('Cancha', on_delete=models.CASCADE)
lote = models.IntegerField()

views.py

class ReservasCreateView(generic.edit.CreateView):
model = Reserva
template_name = 'reservar.html'
fields = ['horario', 'cancha', 'lote']

reservation.html

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Reservar">
</form>

还有一个疑问,如果我想更改表单中的某些输入类型,我应该保留默认的 CreateView 并在 View 上修改它,还是在 forms.py 中创建自定义表单并将其作为 form_class 传递。有什么建议?谢谢

最佳答案

您可以通过添加以下内容强制创建预订日期在数据库级别唯一:

horario = models.DateTimeField(unique=True)

或者,您可以覆盖 form_valid() 方法以检查日期是否被选中并引发异常或任何您想要的:

from django.contrib import messages # better than raising an exception
from app_name import models # import your APP models

class ReservasCreateView(generic.edit.CreateView):
model = Reserva
template_name = 'reservar.html'
fields = ['horario', 'cancha', 'lote']
success_url = 'YOUR_SUCCESS_URL'

def form_valid(self, form):
date = form.cleaned_data.get('horario', None)
# check if the date is unique
# If we find the same date stored in the database
# we'll add a message to be rendered into the template
dates = models.Reserva.objects.filter(horario=date).first()
if dates:
messages.error(self.request, "This current date is not unique!")
return super().form_valid(form)

然后在您的模板中,您可以像这个例子一样添加消息框架:

{% for message in messages %}
{{ message }}
{% endfor %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Reservar">
</form>

欲了解更多信息,您可以访问 django official documentation

关于python - 验证 CreateView 表单中日期时间输入的唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53877266/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com