sqlite 通过Models Django创建表的问题

41ik7eoe  于 2023-06-23  发布在  SQLite
关注(0)|答案(1)|浏览(121)

我正在Django上做一个酒店网站(教育项目)。我有BookingForm(ModelsForm)和Booking(models.Model)。虽然表单工作正常(我调试过了,数据是有效的),但我的表单没有在默认的Django数据库sqllite 3中创建Booking表,它从来没有出现在管理面板中。
models.py

from django.db import models

import datetime

from django.db.models import EmailField
from django.core.validators import EmailValidator, RegexValidator

ROOM_TYPES = [
    ('1', "Single - 200"),
    ('2', "Double - 350"),
    ('3', "Twin - 350"),
    ('4', "Double-Double - 600"),
    ('5', "King Room - 450"),
    ('6', "Luxury - 800")
]
GUESTS_NUMBER = [
    ('1', "1 person. Single comfort room"),
    ('2', "2 people. Recommended Double, Twin or King room"),
    ('3', "3 people. Double-Double or Luxury will match your needs"),
    ('4', "4 people. Double-Double or Luxury will match your needs"),
    ('5', "5 people. Our Luxury room is for you!")
]
STAT = [
    ('0', "Waits for payment"),
    ('1', "Paid")
]

class Booking(models.Model):
    check_in = models.DateField(default=datetime.date.today())
    check_out = models.DateField(default=datetime.date.today())
    room_type = models.CharField(max_length=200, choices=ROOM_TYPES, default=2)
    guests_number = models.CharField(max_length=200, choices=GUESTS_NUMBER, default=2)
    name = models.TextField(max_length=50)
    surname = models.TextField(max_length=100)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone = models.CharField(validators=[phone_regex], max_length=17, blank=True)
    email = EmailField(max_length=254, blank=False, validators=[EmailValidator()])
    payment_status = models.CharField(max_length=200, choices=STAT, default='0')

    def __str__(self):
        return self.surname

forms.py

from app.models import Booking
from django.forms import ModelForm
from django_flatpickr.widgets import DatePickerInput

class BookingForm(ModelForm):

    class Meta:
        model = Booking
        fields = ["check_in", "check_out", "room_type", "guests_number", "name", "surname", "phone", "email", ]
        widgets = {
            "check_in": DatePickerInput(),
            "check_out": DatePickerInput(),
        }

views.py

from django.http import HttpResponse
from django.shortcuts import render

from app.forms import BookingForm

# Create your views here.
def home(request):
    form = BookingForm()
    return render(request, "index.html", {'form': form})

def book(request):
    if request.method == 'POST':
        form = BookingForm(request.POST)
        if form.is_valid():
            new_booking = form.save()
            return HttpResponse('form had gone')
        else:
            return HttpResponse('bad')
    else:
        return render(request, "index.html", {'form': BookingForm()})

网站首页>关于我们

<section class="page-section" id="contact">
    <div class="container">
        <div class="text-center">
            <h2 class="section-heading text-uppercase">Ready to book?</h2>
            <h3 class="section-subheading text-muted">Select all necessaries, we'll take care of your comfort</h3>
        </div>
        <form method="POST" action={% url 'booking_confirmation' %} class="booking-form">
          {% csrf_token %}
          <div class="container">
            <div class="row">
              <div class="col-md-6">
                <div class="calendar-container">
                  <div class="date-fields">
                    <div class="form-group">
                      <label for="check_in">Check-in Date:</label>
                      <input type="text" id="check_in" name="check_in" readonly class="form-control">
                    </div>

                    <div class="form-group">
                      <label for="check_out">Check-out Date:</label>
                      <input type="text" id="check_out" name="check_out" readonly class="form-control">
                    </div>
                  </div>
                </div>
                <div class="form-group">
                    <label for="room_type">Room Type:</label>
                    <select id="room_type" name="room_type" required class="form-control">
                      <option value="1">1 person. Single comfort room</option>
                      <option value="2">2 people. Recommended Double, Twin or King room</option>
                      <option value="3">3 people. Double-Double or Luxury will match your needs</option>
                      <option value="4">4 people. Double-Double or Luxury will match your needs</option>
                      <option value="5">5 people. Our Luxury room is for you!</option>
                    </select>
                </div>
                <div class="form-group">
                  <label for="guests_number">Number of people:</label>
                  <select id="guests_number" name="guests_number" required class="form-control">
                      <option value="1">1</option>
                      <option value="2">2</option>
                      <option value="3">3</option>
                      <option value="4">4</option>
                      <option value="5">5</option>
                    </select>
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-group">
                  <label for="name">Name:</label>
                  <input type="text" id="name" name="name" required class="form-control">
                </div>

                <div class="form-group">
                  <label for="surname">Surname:</label>
                  <input type="text" id="surname" name="surname" required class="form-control">
                </div>

                <div class="form-group">
                  <label for="phone">Mobile Phone:</label>
                  <input type="tel" id="phone" name="phone" required class="form-control">
                </div>

                <div class="form-group">
                  <label for="email">Email:</label>
                  <input type="email" id="email" name="email" required class="form-control">
                </div>
              </div>

                    <button style="opacity: 1!important;" class="btn btn-primary btn-xl text-uppercase" id="submitButton" type="submit">Send Message</button>

            </div>
          </div>
        </form>
    </div>
</section>

<!-- JS for flatpickr -->
 <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
        <script>
        const checkInField = document.getElementById('check_in');
        const checkOutField = document.getElementById('check_out');

        flatpickr("#check_in", {
          minDate: "today",
          dateFormat: "Y-m-d",
          onClose: function(selectedDates, dateStr, instance) {
            if (selectedDates.length > 0) {
              const checkInDate = selectedDates[0];
              const adjustedCheckInDate = new Date(checkInDate.getTime() + (24 * 60 * 60 * 1000));
              checkInField.value = adjustedCheckInDate.toISOString().split('T')[0];
              flatpickr("#check_out", {
                minDate: adjustedCheckInDate,
                dateFormat: "Y-m-d",
                onClose: function(selectedDates, dateStr, instance) {
                  if (selectedDates.length > 0) {
                    const checkOutDate = selectedDates[0];
                    const adjustedCheckOutDate = new Date(checkOutDate.getTime() + (24 * 60 * 60 * 1000));
                    checkOutField.value = adjustedCheckOutDate.toISOString().split('T')[0];
                  } else {
                    checkOutField.value = '';
                  }
                }
              });
            } else {
              checkInField.value = '';
              checkOutField.value = '';
            }
          }
        });
        </script>

首先,错误与数据有效性有关,我修复了它。我不得不拒绝使用PhoneNumberField来进行regex验证,而表单发送是有效的,所以我害怕打破这种脆弱的和谐))现在,debug进入块“form.isvalid():”,传递“newbooking = form.save()”并返回积极的http响应。所以我不知道为什么它成功地通过了第二步,但没有创建模型(表)。也许,在Django中有一些配置可以调用sqllite....IDK

  • 我希望我的表单看起来和index.html一样,模型有它的所有字段,但是表是由post request(form)创建和填充的。如果你知道如何在“www.example.com *_valid()"之后避免“return HttpResponse()”form.is,请也分享这个信息。我想重定向成功页面或发出消息,但比我得到的错误需要使用HttpResponse。

求你了,救救我,我绝望了。我需要任何新鲜的,最好是正确的和有益的想法

xzabzqsa

xzabzqsa1#

对不起,伙计们,问题是非常愚蠢的-我忘记注册预订模型在admin.py.这里是一个代码,如果它是有用的

from django.contrib import admin
from .models import Booking

admin.site.register(Booking)

相关问题