django火车预订系统(预订车票)

时间:2019-08-24 14:47:06

标签: python django

我已经为火车(预订车票)建立了一个django预订系统,但一次只能预订1人,现在我跌倒了,因为这样还不够,我需要让用户能够选择要预订的车票数量(从1到9列出),然后可以在选择行程后以相同的形式预订这些多张车票

我卡住了

Urls.py

from django.urls import path, include, re_path

from . import views

urlpatterns = [

    path('tickets/<int:ticket_id>/',views.tickets_page, name='tickets'),
    path('trips/<int:trip_id>/',views.trips_page, name='trips'),
    re_path(r'^from/(?P<start_station>[0-9]{1,50})/$', views.details_page, name='details_page'),
    path('', views.details_page, name='booking'),    
]

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.core.exceptions import ValidationError
from .models import Ticket, Trip
from django.http import Http404
from django.shortcuts import get_object_or_404

import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

# Create your views here.
def details_page(request):
    if request.method == 'GET':
        end_station_id = request.GET.get('station')
    elif request.method == 'POST':
        end_station_id = request.POST.get('to_station')
    #print(request.GET.get('to_station'))
    trips = Trip.objects.filter(end_station_id=end_station_id)
    context = {'trips' : trips}
    return render(request, 'details/details.html', context)


def trips_page(request, trip_id):
    trip = get_object_or_404( Trip,pk=trip_id)
    error = None
    ticket = None
    if request.method == 'POST':
        first_name = request.POST.get('first_name')
        middle_name = request.POST.get('middle_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        gender = request.POST.get('gender')
        ticket = Ticket(trip=trip,first_name=first_name, middle_name=middle_name,
            last_name=last_name, email=email,gender=gender)
        try:
            ticket.full_clean()
            ticket.save()
            return redirect('tickets',ticket_id=ticket.id)
        except ValidationError as e:
            error = dict(e)
            print(e)
    context = {'trip' : trip, 'error':error, 'ticket':ticket }
    return render(request, 'details/trips.html', context)



def tickets_page(request, ticket_id):
    try:
        ticket = Ticket.objects.get(pk=ticket_id)
    except Ticket.DoesNotExist:
        raise Http404("Ticket does not exist")
    return render(request, 'details/tickets.html', {'ticket': ticket})



models.py

from django.db import models
from datetime import datetime
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator


# Create your models here.
def validate_string(value):
    if value.isalpha():
        print('Good')
    else:
        raise ValidationError(
            ('Enter a valid name!'),
            params={'value': value},
        )

class Station(models.Model):
    name = models.CharField(null=True, max_length=100)

    def __str__(self):
        return "{}".format(self.name)




class Train(models.Model):
    name = models.CharField(null=True, max_length=100)
    seats = models.IntegerField()

    def __str__(self):
        return "{}".format(self.name)



class Trip(models.Model):
    train = models.ForeignKey(Train, related_name="trip_train", null=True, on_delete=models.CASCADE)
    start_station = models.ForeignKey(Station, related_name="start_station" ,on_delete=models.CASCADE, null=True)
    end_station = models.ForeignKey(Station, related_name="end_station" ,on_delete=models.CASCADE, null=True)
    start_time_date = models.DateTimeField()
    end_time_date = models.DateTimeField()
    price = models.DecimalField(max_digits=10, decimal_places=2)


    def __str__(self):
        return "Start: {} - End: {} - Train: {}".format(self.start_station, self.end_station, self.train)



class Passenger(models.Model):
    TICKETS_NUMBER = (
        (1,'1'),
        (2,'2'),
        (3,'3'),
        (4,'4'),
        (5,'5'),
        (6,'6'),
        (7,'7'),
        (8,'8'),
        (9,'9'),
    )


    tickets_number = models.IntegerField(default=1, choices=TICKETS_NUMBER)
    #ticket_ptr = models.OneToOneField(null=True, auto_created=True, default='', on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=False, serialize=False, to='details.Ticket')
    def __str__(self):
        return "{}".format(self.tickets_number)



class Ticket(models.Model):
    GENDER = (
        ('m', 'Male'),
        ('f', 'Female'),
    )

    trip = models.ForeignKey(Trip, related_name="tickets", null=True, on_delete=models.CASCADE)
    booking_time = models.DateTimeField(auto_now_add=True, blank=True)
    first_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False)
    middle_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False)
    last_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False)
    email = models.EmailField(max_length=70,blank=True, null= True)
    gender = models.CharField(max_length=1, choices=GENDER)
    passengers = models.ManyToManyField(Passenger)

    def __str__(self):
        return "{}".format(self.first_name)











0 个答案:

没有答案