如何在Django,Python中将其他应用程序的models.py中的新字段添加到html中

时间:2019-09-19 05:10:38

标签: python django

我想更改字段。

我有预订应用程序的email.html和订单应用程序的order_detail.html。 这两个文件在页面底部都有一个“幼儿园信息”一词。

我想在两个html文件的“托儿所信息”字样下使用服务应用程序中的托儿所字段。

我写了order.nursery,但没有显示。另一个类似order.shippingAddress1可能会出现。 如何像其他任何人一样显示order.nursery?

我的关系应用程序名称是预订,订单,服务。

这是预订应用程序模板的email.html。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>New Reservation #{{ transaction.id }} - TS</title>
        <style>
            table {
                width: 60%;
                margin: 0 auto;
                border-collapse: collapse;
            }
            table tr td {
                border: 1px solid #c1c1c1;   
            }
            p {
                padding-right: 50px;
                padding-left: 50px;   
            }
        </style>
    </head>
    <body>
        <center>
            <h1>Thanks for reserve with us</h1>
            <p>This email is to confirm that you have reserved on the TS.<br>Please make sure that all the details of your order are correct.</p>
        </center>
        <br>
        <table>
            <tr>
                <td valign="top" colspan="2" style="width: 50%;">
                    <b>Your Address:</b><br>
                    {{ transaction.billingName }}<br>
                    {{ transaction.billingAddress1 }}<br>
                    {{ transaction.billingCity }}<br>
                    {{ transaction.billingPostcode }}<br>
                    {{ transaction.billingCountry }}<br>
                </td> 
                <td valign="top" colspan="2" style="width: 50%;">
                    <b>Reservation: </b>#{{ transaction.id }}<br>
                    <b>Date: </b>{{ transaction.created|date:"d M Y"}}
                </td>    
            </tr>

            <tr>
                <td colspan="3" style="text-align: right;"><b>Total</b></td>
                <td>${{ transaction.total }}</td>
            </tr>
              <tr>
                <td colspan="3" style="text-align: right;"><b>Total paid</b></td>
                <td>${{ transaction.total }}</td>
            </tr>
            <tr>
                <td valign="top" colspan="2" style="width: 50%;">
                    <b>Nursery information:</b><br>
                    {{ transaction.nursery }}<br>
                    {{ transaction.shippingAddress1 }}<br>
                    {{ transaction.shippingCity }}<br>
                    {{ transaction.shippingPostcode }}<br>
                    {{ transaction.shippingCountry }}<br>
                </td>  
                <td valign="top" colspan="2" style="width: 50%;">
                    <b>Payment details:</b><br>
                    ${{ transaction.total }} was paid successfully via Stripe.
                </td>
            </tr>
        </table>
        <center>
            <br>
            <p>If you are a registered customer and want to check your order history, please <a href="http://127.0.0.1:8000/account/login/">sign in</a>.<br>Otherwise <a href="http://127.0.0.1:8000/account/create/">sign up</a> to create a new account with us.</p>
        </center>
    </body>
</html>

这是订单应用模板的order_detail.html。

{% extends "base.html" %}
{% load staticfiles %}
{% block title %}
    Order Details - Travel Sitter
{% endblock %}
{% block content %}
    <div>
        <div class="text-center">
            <br>
            <h1 class="text-center my_title">Order Details</h1>
            <br>
            <table class="table table-bordered">
                <tr>
                    <td class="text-left" colspan="2">
                        <b>Order: </b>#{{ order.id }}<br>
                        <b>Date: </b>{{ order.created|date:"d M Y" }}<br>
                        <b>Order Total: </b>${{ order.total }}<br>
                        <b>Order Status: </b><i class="fas fa-check"></i>Complete.
                     </td>  
                     <td class="text-left" colspan="2">
                         <b>Billing Address: </b><br>
                         {{ order.billingName }}<br>
                         {{ order.billingAddress1 }}<br>
                         {{ order.billingCity }}<br>
                         {{ order.billingPostcode }}<br>
                         {{ order.billingCountry }}<br>
                     </td>
                 </tr>
                 <tr>
                     <td><b>Sitting Description</b></td>
                     <td><b>Qty</b></td>
                     <td><b>Unit Price</b></td>
                     <td><b>Sub-Total</b></td>
                 </tr>
                 {% for item in order_items %}
                 <tr>
                     <td>{{ item.sitting }}</td>
                     <td>{{ item.quantity }}</td>
                     <td>{{ item.price }}</td>
                     <td>{{ item.sub_total }}</td>
                  </tr>
                  {% endfor %}
                  <tr>
                      <td class="text-right" colspan="3"><b>Total</b></td>
                      <td>${{ order.total }}</td>
                  </tr>
                  <tr>
                      <td class="text-right" colspan="3"><b>Total Paid</b></td>
                      <td>${{ order.total }}</td>
                  </tr>
                  <tr>
                      <td class="text-left" colspan="2">
                          <b>Nursery information: </b><br>
                          {{ order.nursery }}<br>
                          {{ order.shippingAddress1 }}<br>
                          {{ order.shippingCity }}<br>
                          {{ order.shippingPostcode }}<br>
                          {{ order.shippingCountry }}<br>
                       </td>
                       <td class="text-left" colspan="2">
                           <b>Payment Details: </b><br>
                           The order #{{ order.id }} has been paid successfully via Stripe.
                       </td>
                   </tr>
               </table>
               <button class="btn btn-secondary" onclick="window.print();"><i class="fas fa-print"></i>Print Order</button>
           </div>
       </div>
       <br>
       <br>
   {% endblock %}

这是我的订单应用程序的models.py。

from django.db import models
from service.models import Nursery


class Order(models.Model):
    token = models.CharField(max_length=250, blank=True)
    total = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='USD Order Total')
    emailAddress = models.EmailField(max_length=250, blank=True, verbose_name='Email Address')
    created = models.DateTimeField(auto_now_add=True)
    billingName = models.CharField(max_length=250, blank=True)
    billingAddress1 = models.CharField(max_length=250, blank=True)
    billingCity = models.CharField(max_length=250, blank=True)
    billingPostcode = models.CharField(max_length=10, blank=True)
    billingCountry = models.CharField(max_length=200, blank=True)
    shippingName = models.CharField(max_length=250, blank=True)
    shippingAddress1 = models.CharField(max_length=250, blank=True)
    shippingCity = models.CharField(max_length=250, blank=True)
    shippingPostcode = models.CharField(max_length=10, blank=True)
    shippingCountry = models.CharField(max_length=200, blank=True)
    nursery = models.ForeignKey(Nursery, on_delete=models.CASCADE, null=True)


    class Meta:
        db_table = 'Order'
        ordering = ['-created']

    def __str__(self):
        return str(self.id)



class OrderItem(models.Model):
    nursery = models.CharField(max_length=250)
    quantity = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='USD Price')
    order = models.ForeignKey(Order, on_delete=models.CASCADE)

    class Meta:
        db_table = 'OrderItem'

    def sub_total(self):
        return self.quantity * self.price

    def __str__(self):
        return self.nursery

这是预订应用程序的views.py。

from django.shortcuts import render, redirect, get_object_or_404
from service.models import Nursery
from .models import Reservation, ReservationItem
from django.core.exceptions import ObjectDoesNotExist
import stripe
from django.conf import settings
from order.models import Order, OrderItem
from django.template.loader import get_template
from django.core.mail import EmailMessage

def _reservation_id(request):
    reservation = request.session.session_key
    if not reservation:
        reservation = request.session.create()
    return reservation

def add_reservation(request, nursery_id):
    nursery = Nursery.objects.get(id=nursery_id)
    try:
        reservation = Reservation.objects.get(reservation_id=_reservation_id(request))
    except Reservation.DoesNotExist:
        reservation = Reservation.objects.create(
                       reservation_id = _reservation_id(request)
         )
        reservation.save()
    try:
        reservation_item = ReservationItem.objects.get(nursery=nursery, reservation=reservation)
        if reservation_item.quantity < reservation_item.nursery.stock:
            reservation_item.quantity += 1
        reservation_item.save()
    except ReservationItem.DoesNotExist:
        reservation_item = ReservationItem.objects.create(
                           nursery = nursery,
                           quantity = 1,
                           reservation = reservation     
             )
        reservation_item.save()
    return redirect('reservation:reservation_detail')

def reservation_detail(request, total=0, counter=0, cart_items = None):
    try:
        reservation = Reservation.objects.get(reservation_id=_reservation_id(request))
        reservation_items = ReservationItem.objects.filter(reservation=reservation, active=True)
        for reservation_item in reservation_items:
            total += (reservation_item.nursery.price * reservation_item.quantity)
            counter += reservation_item.quantity
    except ObjectDoesNotExist:
        pass

    stripe.api_key = settings.STRIPE_SECRET_KEY
    stripe_total = int(total * 100)
    description = 'Travel Sitter - Reserve'
    data_key = settings.STRIPE_PUBLISHABLE_KEY
    if request.method == 'POST':
      #  print(request.POST)
       try:
          token = request.POST['stripeToken']
          email = request.POST['stripeEmail']
          billingName = request.POST['stripeBillingName']
          billingAddress1 = request.POST['stripeBillingAddressLine1']
          billingcity = request.POST['stripeBillingAddressCity']
          billingPostcode = request.POST['stripeBillingAddressZip']
          billingCountry = request.POST['stripeBillingAddressCountryCode']
          shippingName = request.POST['stripeShippingName']
          shippingAddress1 = request.POST['stripeShippingAddressLine1']
          shippingcity = request.POST['stripeShippingAddressCity']
          shippingPostcode = request.POST['stripeShippingAddressZip']
          shippingCountry = request.POST['stripeShippingAddressCountryCode']
          customer = stripe.Customer.create(
                      email=email,
                      source = token
              )
          charge = stripe.Charge.create(
                      amount=stripe_total,
                      currency="usd",
                      description=description,
                      customer=customer.id
              )

          try:
              order_details = Order.objects.create(
                      token = token,
                      total = total,
                      emailAddress = email,
                      billingName = billingName,
                      billingAddress1 = billingAddress1,
                      billingCity = billingcity,
                      billingPostcode = billingPostcode,
                      billingCountry = billingCountry,
                      shippingName = shippingName,
                      shippingAddress1 = shippingAddress1,
                      shippingCity = shippingcity,
                      shippingPostcode = shippingPostcode,
                      shippingCountry = shippingCountry
                  )
              order_details.save()
              for order_item in reservation_items:
                 oi = OrderItem.objects.create(
                         nursery = order_item.nursery.name,
                         quantity = order_item.quantity,
                         price = order_item.nursery.price,
                         order = order_details 
                     )
                 oi.save()

                 nurseries = Nursery.objects.get(id=order_item.nursery.id)
                 nurseries.stock = int(order_item.nursery.stock - order_item.quantity)
                 nurseries.save()
                 order_item.delete()

                 print('The Reservation has been created')
              try:
                 sendEmail(order_details.id)
                 print('The order email has been sent to the customer.')   
              except IOError as e:
                  return e    
              return redirect('order:thanks', order_details.id)
          except ObjectDoesNotExist:
               pass 

       except stripe.error.CardError as e:
           return False,e
    return render(request, 'reservation.html', dict(reservation_items = reservation_items, total = total, counter = counter, data_key = data_key, stripe_total = stripe_total, description = description))


def reservation_remove(request, nursery_id):
    reservation = Reservation.objects.get(reservation_id=_reservation_id(request))
    nursery = get_object_or_404(Nursery, id=nursery_id)
    reservation_item = ReservationItem.objects.get(nursery=nursery, reservation=reservation)
    if reservation_item.quantity > 1:
        reservation_item.quantity -= 1
        reservation_item.save()
    else:
        reservation_item.delete()
    return redirect('reservation:reservation_detail')  


def full_remove(request, nursery_id):
    reservation = Reservation.objects.get(reservaton_id=_reservation_id(request))
    nursery = get_object_or_404(Nursery, id=nursery_id)
    reservation_item = ReservationItem.objects.get(nursery=nursery, reservation=reservation)
    reservation_item.delete()
    return redirect('reservation:reservation_detail')

def sendEmail(order_id):
    transaction = Order.objects.get(id=order_id)
    order_items = OrderItem.objects.filter(order=transaction)
    try:
        subject = "Travel Sitter - Reservation #{}".format(transaction.id)
        to = ['{}'.format(transaction.emailAddress)]
        from_email = "orders@travelsitter.com"
        order_information = {
        'transaction' : transaction,
        'order_items' : order_items                       
        }
        message = get_template('email/email.html').render(order_information)
        msg = EmailMessage(subject, message, to=to, from_email=from_email)
        msg.content_subtype = 'html'
        msg.send()
    except IOError as e:
        return e

这是服务应用程序的models.py。

from django.db import models
from django.urls import reverse

class City(models.Model):
    name = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to='city', blank=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'city'
        verbose_name_plural = 'cities'

    def get_url(self):
        return reverse('service:sittings_by_city', args=[self.slug])

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


class Nursery(models.Model):
    name = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    image = models.ImageField(upload_to='nursery', blank=True)
    stock = models.IntegerField()
    available = models.BooleanField(default=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'nursery'
        verbose_name_plural = 'nurseries'

    def get_url(self):
        return reverse('service:SittingDetail', args=[self.city.slug, self.slug])

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

这是预订应用程序的models.py。

from django.db import models
from service.models import Nursery

class Reservation(models.Model):
    reservation_id = models.CharField(max_length=250, blank=True)
    date_added = models.DateField(auto_now_add=True)
    class Meta:
        db_table = 'Reservation'
        ordering = ['date_added']

    def __str__(self):
        return self.reservation_id

class ReservationItem(models.Model):
    nursery = models.ForeignKey(Nursery, on_delete=models.CASCADE)
    reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    active = models.BooleanField(default=True)
    class Meta:
        db_table = 'ReservationItem'

    def sub_total(self):
        return self.nursery.price * self.quantity

    def __str__(self):
        return self.nursery

我非常感谢您每次的好意。 如果我必须显示其他文件,请教我。

1 个答案:

答案 0 :(得分:0)

由于苗圃 Order 模型类中的外键。这意味着Nursery模型类与 Order 类具有一对多关系。为了访问html文件中的Nursery模型类属性,您可以使用订单对象和Nursery键来实现。

For Example:
order.nursery.name: This would return the name of Nursery.

以类似的方式,您可以访问html文件中的所有其他Nursery属性。