I have a form users can fill out to reserve a table at a restaurant. However when they submit the form no data gets sent to the admin side.
I have watched some tutorials and read other posts on this site and nothing seems to fix it. I feel like it is something so small but I just cant figure it out.
views.PY
from django.shortcuts import render, get_object_or_404
from django.views import generic, View
from .models import Book
from .forms import BookForm
from django.http import HttpResponseRedirect
def Book(request):
"""
Renders the book page
"""
if request.user.is_authenticated:
form = BookForm(request.POST or None)
context = {
"form": form,
}
else:
return HttpResponseRedirect("accounts/login")
book_form = BookForm(data=request.POST)
if book_form.is_valid():
instance = book_form.save(commit=False)
instance.save()
else:
book_form = BookForm()
return render(
request,
"book.html",
{
"book_form": BookForm(),
}
)
models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
from cloudinary.models import CloudinaryField
class Book(models.Model):
name = models.CharField(max_length=50)
number_of_guests = models.PositiveIntegerField(validators=[MinValueValidator(1)])
date = models.DateTimeField()
email = models.EmailField()
requests = models.TextField(max_length=200)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
approved = models.BooleanField(default=False)
class Meta:
ordering = ['date']
def __str__(self):
return f"{self.date} for {self.name}"
forms.py
from .models import Book
from django import forms
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = (
'name',
'number_of_guests',
'date',
'email',
'requests',
)
CodePudding user response:
Try this view:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect,render
@login_required(login_url="accounts/login")
def Book(request):
if request.method=="POST":
book_form = BookForm(request.POST)
if book_form.is_valid():
book_form.save()
return redirect("some_success_page")
else:
return redirect("some_error_page")
else:
book_form = BookForm()
return render(
request,
"book.html",
{
"book_form": book_form,
}
)
In settings.py
LOGIN_URL="accounts/login"