Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate datetime input uniqueness in CreateView form

Tags:

python

django

I have this model, and what I need is the time to be unique as it's a Reservation, so when I create a new reservation, how can I check if that time is already picked.

models.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>

And another doubt I have, if I want to change some input types in the form, should I keep the default CreateView and modify it over the view, or create a custom form in forms.py and pass it as form_class. What's the recomendation? Thanks

like image 309
federico Avatar asked Mar 24 '26 13:03

federico


1 Answers

You can force the creation of reservations's date to be unique in the database level by adding:

horario = models.DateTimeField(unique=True)

Or, you can override the form_valid() method in order to check if the date is picked or not and rise an exception or whatever you want:

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)

And then in your template you can add the messages framework like this example:

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

For more information you can visit the django official documentation

like image 57
Chiheb Nexus Avatar answered Mar 27 '26 01:03

Chiheb Nexus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!