【问题标题】:How to render a page based on the button clicked on another page django如何根据单击另一个页面django的按钮来呈现页面
【发布时间】:2021-10-02 20:11:30
【问题描述】:

我有一个这样的页面

    {% for product in products %}
        <div class="col-lg-4">
        <img alt="" class="thumbnail" src="{{ product.images.all.0.image.url }}">
            <div class="box-element product">
                <h5><strong>{{ product.name }}</strong></h5>
                <hr>
                <button data-product="{{ product.id }}" data-action="add"
                        class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>

                <a data-product="{{ product.id }}" data-action="Save" class="btn btn-outline-secondary detail"
                   href="{% url 'detail' %}"> Detail</a>
                .....

当用户点击详细信息时,它应该根据他点击的详细信息按钮转到另一个页面以显示产品的详细信息,所以我制作了这样的 detail.js 文件

var detailBtns = document.getElementsByClassName("detail") //get all add to cart button with class update-cart

for (i = 0; i < detailBtns.length; i++) {
    detailBtns[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId )
        console.log(current_user)
        GetDetail(productId, action) // this function will be called and will pass product id and action in body to your view for further processing.
    })
}

function GetDetail(productId, action){
console.log("func")
    var url = '/detail/'

    fetch(url, {
        method: 'POST',
        headers:{
            'content-Type':'application/json',
            'X-CSRFToken':csrftoken,
        },
        body:JSON.stringify({"productId": productId, "action": action})
    })
    .then((response) =>{
        return response.json()
    })

    .then((data) =>{
        console.log('data:',data)
        location.reload()
    })

}

views 中有一个函数连接到 URL detail/

def detail(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    product = Product.objects.get(id=productId)
    context = {
        'product':product
    }
    print(productId)
    return render(request, 'detail.html', context)

但是当我点击任何产品的详细信息时出现错误“JSONDecodeError。预期值:第1行第1列(字符0)”

【问题讨论】:

  • 你能分享一下request.body有什么吗?

标签: javascript html json django render


【解决方案1】:

Generic Views 会让你的生活变得如此简单。您可以通过几行代码实现相同的功能。通用视图执行非常常见的任务,例如“显示模型中的所有项目”或“显示特定模型实例的详细信息”(您在这里要做的两件事)并抽象出大部分繁琐的实现细节。如果您的应用很简单,请使用它们

这将使您的生活更轻松:

在您的第一页视图中使用List View

from django.views.generic.list import ListView

class ProductListView(ListView):
  model = Product
  context_object_name = "products"
  template_name = "yourListTemplate.html"

您可以保持模板不变,因为上下文对象名称已更改为产品

使用Detail View为每个产品创建产品详细信息页面

基本上你只需要告诉视图使用哪个模型,并将模型实例的 id 作为 url 参数传递,它就会让你在模板中访问该实例

from django.views.generic.detail import DetailView

class ProductDetailView(DetailView):
  model = Product
  context_object_name = "product"
  template_name = "yourDetailTemplate.html"

在你的 urls.py 中

from .views import ProductListView, ProductDetailView

urlpatterns = [
  #...
  path("listViewEndpoint/", ProductListView.as_view(), name="productList"),
  path("detailViewEndpoing/<int:pk>/", ProductDetailView.as_view(), name="productDetail"),
]

和 yourListTemplate.html

把那个标签改成这个

<a href="{% url 'productDetail' product.pk %}">Detail</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多