如何从 onclick 获取模型 ID

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


models.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

views.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 %}


千万里不及你
浏览 119回答 1
1回答

小怪兽爱吃肉

您需要修改您的urls.py代码以接受一个 id 以及storeex:store/1并在您的home.html更改网址中从<a href="{% url 'store' %}"> View</a></button>到<a href="{% url 'store' business.id %}"> View</a></button>Urls.pyurlpatterns = [&nbsp; &nbsp; # ...&nbsp; &nbsp; path('store/<int:id>/', views.store),&nbsp; &nbsp; # ...]Views.pydef store(request, id):&nbsp; &nbsp; menus=Menu.objects.filter(business_id=id)&nbsp; &nbsp; context={'menus':menus}&nbsp; &nbsp; return render(request,"foodapp/store.html",context){% for menus in menu %}并修复store.html 中的错误:{% for menu in menus %}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python