Home > Software engineering >  Django form is never valid and hence doesnt save to database
Django form is never valid and hence doesnt save to database

Time:11-17

I am creating a registration model which has date,time(charfield with choices),customer and restaurant .I need some help on why my instance is not saved even when I fill out my model form

models.py

class reservation(models.Model):
    TIMESLOTS = [
        ('11:00-1:00', '11:00-1:00'),
        ('01:00-3:00', '01:00-03:00'),
        ('03:00-05:00', '03:00-05:00'),
        ('05:00-07:00', '05:00-07:00'),
        ('07:00-09:00', '07:00-09:00')
    ]

    date=models.DateField(null=True)
    time=models.CharField(null=True,max_length=200,choices=TIMESLOTS)
    customer=models.OneToOneField(User,null=True,on_delete=models.CASCADE)
    restaurant=models.OneToOneField(Restaurantdetails,on_delete=models.CASCADE,null=True)

    def __str__(self):
        return self.restaurant.name

forms.py

class Reservationform(ModelForm):

    class Meta:

        model=reservation
        fields=['date','time','restaurant']

views.py

def reservationcreator(request):
    form=Reservationform()

    if form.is_valid():
        form = Reservationform(request.POST)

        res=form.save()
        res.customer=request.user
        res.save()
        messages.success(request, 'reservation created')
        return redirect('menu')
    else:
        print('BS')
    context = {'form': form}

    return render(request,'userrestaurant/reservation.html',context)

CodePudding user response:

Your form will never be valid because you are supplying an empty form. You need to add the request.POST data to that form before you validate it:

def reservationcreator(request):
    form=Reservationform(request.POST or None)

    if form.is_valid():
        res.customer=request.user
        res=form.save()
        messages.success(request, 'reservation created')
        return redirect('menu')
    else:
        print('BS')
    context = {'form': form}

    return render(request,'userrestaurant/reservation.html',context)

CodePudding user response:

A form that is not bounded, is never valid. A bounded form is a form that received data, for example through request.POST or request.GET; and request.FILES. You thus check the HTTP method, and depending on that initialize the form, so:

def reservationcreator(request):
    if request.method == 'POST':
        form = Reservationform(request.POST, request.FILES)
        if form.is_valid():
            form.instance.customer = request.user
            form.save()
            messages.success(request, 'reservation created')
            return redirect('menu')
    else:
        form = ReservationForm()
    context = {'form': form}
    return render(request, 'userrestaurant/reservation.html', context)

That being said, your view is a simple CreateView [Django-doc] and can be implemented with:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse
from django.views.generic import CreateView

class ReservationCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    form_class = ReservationForm
    template_name = 'userrestaurant/reservation.html'
    success_url = reverse('menu')
    success_message = 'reservation created'

    def form_valid(self, form):
        form.instance.customer = request.user
        return super().form_valid(form)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

  • Related