簡體   English   中英

如何將其他應用程序的 models.py 中的新字段添加到 Django、Python 中的 html

[英]How can I add a new field from the other app's models.py to html in Django, Python

我想換個領域。

我有預訂應用程序的 email.html 和訂單應用程序的 order_detail.html。 這兩個文件都有一個詞苗圃信息:在頁面的底部。

我想在兩個 html 文件的 Nursery 信息下使用服務應用程序中的 Nursery 字段。

我寫了 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

我真的很感謝你每次的好意。 如果我必須顯示其他文件,請教我。

由於nursery順序model class中的ForeignKey。 這意味着 Nursery model class 與訂單class 具有一對多關系。 為了訪問 html 文件中的 Nursery model class 屬性,您可以使用訂單 ZA8CFDE6331BD59EB266696

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

以類似的方式,您可以訪問 html 文件中的所有其他 Nursery 屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM