首页 > 解决方案 > Django 模型保存表单但不显示

问题描述

您好我已经创建了一个地址模型并将该模型链接到表单并创建了视图。但该表格确实保存了任何数据,但该数据没有显示给我。尽管它向我显示了终端中的数据。这是我的地址模型:

from django.db import models
from billing.models import BillingProfile
# Create your models here.
ADDRESS_TYPES = (
    ('billing' , 'Billing'),
    ('shipping' , 'Shipping'),
)


class Address(models.Model):
    billing_profile     = models.ForeignKey(BillingProfile , on_delete=models.CASCADE)
    addresss_type        = models.CharField(max_length=120 , choices=ADDRESS_TYPES)
    address_line_1      = models.CharField(max_length=120)
    address_line_2      = models.CharField(max_length=120 , null=True , blank= True)
    city                = models.CharField(max_length=120)
    country             = models.CharField(max_length=120 ,default='Pakistan')
    postal_code         = models.CharField(max_length=120)

    def __str__(self):
        return str(self.billing_profile)
因为我将地址模型与 billingprofile 连接起来,所以计费模型是:

class BillingProfile(models.Model):
    user        = models.OneToOneField(User ,null=True , blank=True , on_delete=models.CASCADE)
    email       = models.EmailField()
    active      =models.BooleanField(default=True)
    update      = models.DateTimeField(auto_now=True)
    time_stamp   = models.DateTimeField(auto_now_add=True)

    objects = BillingProfileManager()

    def __str__(self):
        return self.email

我将我的地址模型 称为 forms.py/address

from django import forms
from .models import Address

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address
        fields = ['address_line_1','address_line_2','city','country','postal_code']

我的地址/views.py 是:

from django.shortcuts import render , redirect
from django.utils.http import is_safe_url
# Create your views here.
from billing.models import BillingProfile
from .forms import AddressForm

def checkout_address_create_view(request):
    form = AddressForm(request.POST or None)
    context = {
        'form':form
    }
    next_ = request.GET.get('next')
    next_post = request.POST.get('next')
    redirect_path = next_ or next_post or None
    if form.is_valid():
        print(request.POST)
        instance = form.save(commit=False)
        billing_profile ,  billing_profile_created = BillingProfile.objects.new_or_get(request)
        if billing_profile is not None:
            instance.billing_profile = billing_profile
            instance.address_type = request.POST.get('address_type','shipping')
            instance.save()
        else:
            print("Error Here")
            return redirect("cart:checkout")

        if is_safe_url(redirect_path , request.get_host()):
            return redirect(redirect_path)
        else:
            return redirect("cart:checkout")
    return redirect("cart:checkout")

我的地址/form.html 是:

现在我的 form.html 是:

<form method="POST" action="{% if action_url%}{{ action_url }} {% else %}{% url 'login' %}{% endif %}">
                {% csrf_token %}
    {% if next_url %}
       <input type="hidden" name="next" value="{{ next_url }}"/>
    {% endif %}

    {% if address_type %}
        <input type="hidden" name="address_type" value="{{ address_type }}"/>
      {% endif %}
                {{form.as_p}}
                <button type="submit" class="btn btn-secondary">Submit</button>
              </form>

并且此表单显示在购物车主页上,因此购物车视图为:

def checkout_home(request):
    cart_obj , cart_created = Cart.objects.new_or_get(request)
    order_obj = None
    if  cart_created or cart_obj.products.count() ==0:
        return redirect("cart:home")
    login_form = LoginForm()
    guest_form = GuestForm()
    address_form =AddressForm()
    billing_address_form = AddressForm()

    billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)
    if billing_profile is not None:
        order_obj , order_obj_created = Order.objects.new_or_get(billing_profile , cart_obj)


    context= {
        "object" : order_obj,
        "billing_profile" : billing_profile,
        "login_form" : login_form,
        "guest_form" :guest_form,
        "address_form" :address_form,
        "billing_address_form" : billing_address_form,

    }

    return render(request , "carts/checkout.html" , context)

我的结帐html是:

{% extends 'base.html' %}

{% block content %}


{{object.order_id}} -- {{object.cart}}

{% if not billing_profile %}
<div class="row text-center">
    <div class="col-12 col-md-6">
        <p class="lead">Login</p>
        {% include 'accounts/snippets/form.html' with form=login_form next_url=request.build_absolute_uri %}
    </div>
    <div class="col-12 col-md-6">
        <p class="lead">Continue as guest</p>

        {% url "guest_register" as guest_register_url %}
        {% include 'accounts/snippets/form.html' with form=guest_form next_url=request.build_absolute_uri action_url=guest_register_url %}
    </div>
    </div>
{% else %}

         {% if not object.shipping_address %}
                <div class="row">
                         <div class="col-md-6 mx-auto col-10">
                             <p class="lead">Shipping Address</p>
                                {% url "checkout_address_create" as checkout_address_create %}
                                {% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='shipping' %}
                          </div>
                </div>
         {% elif not object.billing_address%}
            <div class="row">
                         <div class="col-md-6 mx-auto col-10">
                             <p class="lead">Billing Address</p>
                                {% url "checkout_address_create" as checkout_address_create %}
                                {% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='billing' %}
                          </div>
            </div>

         {% else %}

                <h1>Finalize Checkout</h1>
            <p>Cart_total:{{object.cart.total}}</p>
            <p>Shipping Total:{{object.shipping_total}}</p>
            <p>Order Total:{{object.total}}</p>
            <button>Checkout</button>
         {% endif %}

{% endif %}
{% endblock %}

标签: pythonhtmldjangowebbackend

解决方案


推荐阅读