如何在多个类别或页面上具有相同的HTML,然后在Django Restframework中添加来自数据库的特定或不同数据?

发布于 2025-02-04 02:18:10 字数 3004 浏览 0 评论 0原文

在此程序中,我在views.py中具有这两个功能:

def home(request):
    p=product.objects.all()
    return render(request,'home.html',{'p':p})

def foods(request):
    p=product.objects.all()
    return render(request,'foods.html',{'p':p})

他们都可以访问数据库中相同的数据,这是指我想使用Django Restframework发布一些JSON,然后 foods 和home将具有相同的数据,因为它们具有相同的html:

    <div class="grid">  
        {% for i in p%} 
                
                    <div class='card'>
                        <img src="{{i.image}}"></img>
                        <p id="id">{{i.description}}</p>
                        <a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'>
                            <button><span class="price"> ${{i.price}}</span> buy</button>
                        </a>    




                    </div>

        {%endfor%}
    </div>

对于我来说,只有一个HTML用于多个页面对我来说是一件好事空,但它将基于JSON产生相同数量的产品,例如home

我想知道如何对多个类别或页面具有相同的HTML,然后将数据库中的特定或不同数据添加到它们中?

更多详细信息:

model.py:

from django.db import models
 
# Create your models here.
class product(models.Model):
     
     
    image=models.CharField(max_length=500)
    description=models.CharField(max_length=500)
    price=models.CharField(max_length=50)
    buy=models.CharField(max_length=100)
 

serializers.py:

from rest_framework import serializers
from .models import product
 


class productSerializer(serializers.ModelSerializer):
    class Meta:
        model= product
        fields="__all__"
 

views.py:

from django.shortcuts import render
from .models import *
from rest_framework import viewsets,status
from .serializers import productSerializer
from rest_framework.parsers import JSONParser
from django.http import HttpResponse,JsonResponse
from rest_framework.response import Response
from rest_framework.decorators import action

class productviewset(viewsets.ModelViewSet):
    queryset=product.objects.all()
    serializer_class = productSerializer 

    def create(self, request):
        serialized = productSerializer(data=request.data, many=True)
        if serialized.is_valid():
            serialized.save()
            return Response(serialized.data, status=status.HTTP_201_CREATED)
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

    @action (detail=False , methods=['post']) 
    def delete(self,request):
        product.objects.all().delete()
        return Response('success')
def home(request):
    p=product.objects.all()
    return render(request,'home.html',{'p':p})

def foods(request):
    p=product.objects.all()
    return render(request,'foods.html',{'p':p})

如果我有20个具有20个不同页面的类别,如果这些类别有一种从同一数据库中专门访问的方法,我将永远不会创建20个不同的数据库。

In this program i have these two functions in my views.py:

def home(request):
    p=product.objects.all()
    return render(request,'home.html',{'p':p})

def foods(request):
    p=product.objects.all()
    return render(request,'foods.html',{'p':p})

They both have access to the same data from database i mean if i want to post some json with django restframework then foods and home will have the same data because they have the same html:

    <div class="grid">  
        {% for i in p%} 
                
                    <div class='card'>
                        <img src="{{i.image}}"></img>
                        <p id="id">{{i.description}}</p>
                        <a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'>
                            <button><span class="price"> ${{i.price}}</span> buy</button>
                        </a>    




                    </div>

        {%endfor%}
    </div>

it is good for me to have just one html for multiple pages and then access to different data from database but if i add some json both of them will contain the same data(for some reason data of foods is empty but it will generate the same number of products based on json like home)

I want to know how can you have same html for multiple categories or pages and then add specific or different data from database to them?

More details:

models.py:

from django.db import models
 
# Create your models here.
class product(models.Model):
     
     
    image=models.CharField(max_length=500)
    description=models.CharField(max_length=500)
    price=models.CharField(max_length=50)
    buy=models.CharField(max_length=100)
 

serializers.py:

from rest_framework import serializers
from .models import product
 


class productSerializer(serializers.ModelSerializer):
    class Meta:
        model= product
        fields="__all__"
 

views.py:

from django.shortcuts import render
from .models import *
from rest_framework import viewsets,status
from .serializers import productSerializer
from rest_framework.parsers import JSONParser
from django.http import HttpResponse,JsonResponse
from rest_framework.response import Response
from rest_framework.decorators import action

class productviewset(viewsets.ModelViewSet):
    queryset=product.objects.all()
    serializer_class = productSerializer 

    def create(self, request):
        serialized = productSerializer(data=request.data, many=True)
        if serialized.is_valid():
            serialized.save()
            return Response(serialized.data, status=status.HTTP_201_CREATED)
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

    @action (detail=False , methods=['post']) 
    def delete(self,request):
        product.objects.all().delete()
        return Response('success')
def home(request):
    p=product.objects.all()
    return render(request,'home.html',{'p':p})

def foods(request):
    p=product.objects.all()
    return render(request,'foods.html',{'p':p})

If i have 20 categories with 20 different pages i will never create 20 different databases if there is a way for those categories to access specifically from the same database.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故人爱我别走 2025-02-11 02:18:10

如果我正确理解了这个问题,并且您将有一定数量的商品分为20个类别,那么我以某种方式使用了
您需要为类别创建一个单独的模型,并且在产品模型中,您需要将外键添加到类别

models.py

class Category(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True)
    
    def get_absolute_url(self):
        return reverse('shop:product_list_by_category',
                        args=[self.slug])

    def __str__(self):
        return self.name



class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products')
    available = models.BooleanField(default=True)
    ...

views.py

def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(available=True)
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)
    return render(request,
                  'shop/product/list.html',
                  {'category': category,
                   'categories': categories,
                   'products': products})

urls.py

from django.urls import path
from . import views

app_name = 'shop'

urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('<category_slug>', views.product_list, name='product_list_by_category'),
]

html

{% block content %}
    <div id="main" class="product-list">
        <h1>{% if category %}{{ category.name }}{% else %}Products{% endif %}</h1>
        {% for product in products %}
            <div class="item">
               <img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}">
            </div>
        {% endfor %}
    </div>
{% endblock %}

If I understand the question correctly and you will have a certain amount of goods divided into 20 categories, then I somehow used this
You need to create a separate model for the categories, and in the product model add a foreign key to the category

models.py

class Category(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True)
    
    def get_absolute_url(self):
        return reverse('shop:product_list_by_category',
                        args=[self.slug])

    def __str__(self):
        return self.name



class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products')
    available = models.BooleanField(default=True)
    ...

views.py

def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(available=True)
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)
    return render(request,
                  'shop/product/list.html',
                  {'category': category,
                   'categories': categories,
                   'products': products})

urls.py

from django.urls import path
from . import views

app_name = 'shop'

urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('<category_slug>', views.product_list, name='product_list_by_category'),
]

html

{% block content %}
    <div id="main" class="product-list">
        <h1>{% if category %}{{ category.name }}{% else %}Products{% endif %}</h1>
        {% for product in products %}
            <div class="item">
               <img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}">
            </div>
        {% endfor %}
    </div>
{% endblock %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文