django 预订网站的问题,无法删除占用的小时数

lb3vh1jj  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(98)

我开始用Django建立我的第一个网站。试图为我女朋友的业务(美甲沙龙)创建网站,并有一些问题。第一个问题是预订表格和选择自由时间。设法找到解决方案与2个模型和一对一的关系:

class FreeHoursModel(models.Model):
    EARLY = '10:00'
    MID = '13:00'
    LATE = '16:00'

    HOURS = [(x, x) for x in (EARLY, MID, LATE)]

    time = models.CharField(
        max_length=20,
        choices=HOURS,
        default=1,
    )
    date = models.DateField(
    )

    def __str__(self):
        return f"{str(self.date)} - {self.time}"

class Customer(models.Model):
    MAX_LENGTH = 25
    name = models.CharField(
        max_length=MAX_LENGTH,
    )
    last_name = models.CharField(
        max_length=MAX_LENGTH,
    )
    phone_number = models.IntegerField()
    date_of_booking = models.DateField(
        auto_now_add=True
    )
    hours = models.OneToOneField(
        FreeHoursModel,
        on_delete=models.DO_NOTHING
    )
    class Meta:
        get_latest_by = 'date_of_booking'

第二个问题是如何消除时间。
以下是我的观点:

class IndexView(generic.TemplateView):
    template_name = 'landing_page/landing_page.html'

class BookingView(generic.CreateView):
    template_name = 'booking_page/booking.html'
    success_url = reverse_lazy('summary')
    form_class = CustomerForm

    def form_valid(self, form):
        name = form.cleaned_data['name']
        last_name = form.cleaned_data['last_name']
        phone_number = form.cleaned_data['phone_number']
        hour = str(form.cleaned_data['hours'])

        # print(hour.encode("utf-8"))
        return super(BookingView, self).form_valid(form)

    def get_success_url(self):
        if self.success_url:
            return self.success_url
        return super().get_success_url()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['customer'] = CustomerForm()

        return context

class SummaryView(generic.TemplateView):
    template_name = 'booking_page/summary.html'

    # if Customer.objects.all():
    #     latest_created_booking = Customer.objects.latest()
    #     latest_taken_hour_id = latest_created_booking.hours_id
    #     latest_taken_hour = FreeHoursModel.objects.filter(id=latest_taken_hour_id)[0]
    #     print(latest_taken_hour)
    #     latest_taken_hour.delete()

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)

    return context

我试图删除与最新创建的客户实体相关的小时数据库实体

# if Customer.objects.all():
    #     latest_created_booking = Customer.objects.latest()
    #     latest_taken_hour_id = latest_created_booking.hours_id
    #     latest_taken_hour = FreeHoursModel.objects.filter(id=latest_taken_hour_id)[0]
    #     print(latest_taken_hour)
    #     latest_taken_hour.delete()

这是succes_url。但是这只在运行项目时删除最后一个实体,而不是在点击SummaryView时。请帮助任何建议

roejwanj

roejwanj1#

这就是我处理这个问题的方法。首先,我将创建三个模型:

  • Customer:负责保存客户信息。
  • WorkHours:白天我们可供预订的时间
  • Booking:保留预订信息。

这也意味着我将创建两个视图:

  • CreateCustomerView:用于创建客户。
  • CreateBookingView:创建预订。

流程如下:
1.让客户在CreateCustomerView中输入其个人详细信息。
1.如果setp 1成功,则将客户重定向到CreateBookingView,他们将在此预约。
1.如果步骤2成功,则重定向到SummaryView
我也会使用Django的ModelForm来使表单创建和数据保存更容易。
下面是我的示例代码:

models.py

值得注意的是Booking模型的Meta类中的unique_together属性。这是为了确保没有hourdate是相同的。所以,如果一个客户在今天的“16:00”预约,其他客户将无法预约。但是如果他们明天预订相同的hour,他们将被允许,因为明天将是免费的。

from django.utils import timezone

def free_hours():
    return [(i, i) for i in "10:00,13:00,16:00".split(",")]

class WorkHour(models.Model):
    hour = models.CharField(max_length=50, choices=free_hours()) # choices can also receive functions that return a sequence object. 

class Customer(models.Model):
    # customer fields: first/last_name, phone_no, etc.

class Booking(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    date = models.DateField(default=timezone.now().date)
    hour = models.ForeignKey(WorkHour, on_delete=models.CASCADE)

    class Meta:
        unique_together = ["date", "hour"]

forms.py

我排除了Booking模型上的customer字段,因为稍后将在视图中设置客户。

from django import forms

class BookingForm(forms.ModelForm):
    class Meta:
        model = Booking
        exclude = ["customer]

class CustomerForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = "__all__"

浏览次数

当我使用基于类的视图时,我喜欢从基View继承,并且在相应的请求方法中继承我的逻辑。我发现这更容易,因为edit视图(如FormViewCreateView)中的抽象更少。
请注意:

  • CreateBookingView正在接受user_pk参数,该参数由CreateCustomerView发送。它被用来获取和设置客户进行此预订。
from django.views.generic import View
from django.shortcuts import redirect, render
from django.urls import reverse

class CreateCustomerView(View):
    template_name = "customer_page/create.html"
    def get(self, request, *args, **kwargs):
        form = CustomerForm()
        return render(request, self.template_name, {"form": form})
    
    def post(self, request, *args, **kwargs):
        form = CustomerForm(request.POST)
        if form.is_valid():
            customer = form.save()
            return redirect("create-booking", kwargs={"user_pk": customer.pk})
        return render(request, self.template_name, {"form": form})

class CreateBookingView(View):
    template_name = "booking_page/booking.html"
    def get(self, request, user_pk, *args, **kwargs):
        form = BookingForm()
        return render(request, self.template_name, {"form": form})
    
    def post(self, request, user_pk, *args, **kwargs):
        form = BookingForm(request.POST)
        if form.is_valid():
            booking = form.save(commit=True)
            booking.customer = Customer.objects.get(pk=user_pk)
            booking.save()
            return reverse("summary")
        return render(request, self.template_name, {"form": form})

url

没有什么奇怪的,我希望这是不言自明的。

from django.urls import path

urlpatterns = [
    path("create/customer/", CreateCustomerView.as_view(), name="create-customer"),
    path("user/<int:user_pk>/book/", CreateBookingView.as_view(), name="create-booking"),
    
]

这个基本设置应该可以正常工作。您可能希望在某些方面改善用户体验。例如,在BookingView中,您只能显示客户选择的日期可用的free hours。这可能是一个很好的练习,可能需要一些JavaScript。

相关问题