首页 > 解决方案 > 如何从 onclick 获取模型 ID

问题描述

嗨,我是 django 的新手,正在尝试建立一个类似 zomato 的网站。我想在点击餐厅按钮时填充餐厅菜单。我有保存所有餐厅数据的商业模式和保存餐厅菜单的菜单模型餐厅名称作为外键,我已将餐厅填充到 home.html,单击特定餐厅后如何将特定餐厅的菜单填充到 store.html 希望我问的是正确的问题,这是我的代码

模型.py

class Business(models.Model):
bname=models.CharField(max_length=200,null=False)
specialities=models.CharField(max_length=200,null=True)
location=models.CharField(max_length=200,null=False)
# image=models.ImageField(null=True,blank=True)

def __str__(self):
    return self.bname

@property
def imageURL(self):

    try:
        url=self.image.url
    except:
        url= ''
    return url

class Menu(models.Model):
    business=models.ForeignKey(Business,on_delete=models.CASCADE,blank=True,null=False)
    dish_name=models.CharField(max_length=200,null=False)
    price=models.IntegerField(null=False)

def __str__(self):
    return self.dish_name

视图.py

def home(request):
businesses= Business.objects.all()
context={'businesses':businesses}

return render(request,"foodapp/home.html",context)

def store(request):
    menus=Menu.objects.get.all()
    context={'menus':menus}
    return render(request,"foodapp/store.html",context)

主页.html

    {% for business in businesses %}
    <div class="col-md-4">
    <div class="box-element product">
    <img  class="thumbnail" src="{% static 'images/assets/placeholder.png' %}" alt="">
    <hr>
    <h6><strong>{{business.bname}}</strong></h6>
    <hr>
    <h6>{{business.specialities}}</h6>
    <h6>{{business.location}} &nbsp;&nbsp;
        <button data-product={{business.id}} data-action="add" class="btn btn-outline-secondary add- 
     btn update-cart">
            <a href="{% url 'store' %}"> View</a></button>
     </h6>
    {% endfor %}

商店.html

{% block content %}

<div class="row">
<div class="container">  
    {% for menus in menu %}   
<div style="margin-top: 20px;" class="col-md-4">
    <div class="box-element product">
    <img  class="thumbnail" src="{% static 'images/assets/placeholder.png' %}" alt="">
    <hr>
    <h6><strong>{{menu.dish_name}}</strong></h6>
    <hr>
    <h6>Type:</h6>
    <button data-product={{}} data-action="add" class="btn btn-outline-secondary add-btn update- 
    cart">
        <a href="{% url 'cart' %}"> Add to Cart</a></button>        
    
        
    <h4 style="display: inline-block; float: right;">{{menu.price}}</h4>
    </div>
  

    </div>
   {% endfor %}
 
   </div>



 {% endblock content %}
            
    

标签: pythondjango

解决方案


您需要修改您urls.py以接受 id 以及storeex:store/1并在您的home.html更改 url 从<a href="{% url 'store' %}"> View</a></button><a href="{% url 'store' business.id %}"> View</a></button>

网址.py

urlpatterns = [
    # ...
    path('store/<int:id>/', views.store),
    # ...
]

视图.py

def store(request, id):
    menus=Menu.objects.filter(business_id=id)
    context={'menus':menus}
    return render(request,"foodapp/store.html",context)

并修复 store.html:{% for menus in menu %}中的错误{% for menu in menus %}


推荐阅读