我想在名为core的django模板应用中显示视图结果,但是它不能正常工作,这是哪里出了问题?
对于两种类别,有两种模型,一种是Category,另一种是AgeRate。类别将根据体裁对书籍进行分类,而年龄率将根据目前包括(A,B,C)比率的年龄比率对书籍进行分类。 现在,在模板中,我将尝试显示年龄率的结果,但无法正常工作。
model.py
class Category(TranslatableModel):
translations = TranslatedFields(
name=models.CharField(max_length=200,
db_index=True),
slug=models.SlugField(max_length=200,
db_index=True,
unique=True),
)
class Meta:
# ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('core:product_list_by_category',
args=[self.slug])
class AgeRate(TranslatableModel):
translations = TranslatedFields(
age_rate=models.CharField(max_length=3),
slug=models.SlugField(max_length=4,
db_index=True,
unique=True, default='')
)
class Meta:
# ordering = ('name',)
verbose_name = 'age_rate'
verbose_name_plural = 'age_rates'
def __str__(self):
return self.age_rate
def get_absolute_url(self):
return reverse('core:product_list_by_age_rate',
args=[self.slug])
class Product(TranslatableModel):
translations = TranslatedFields(
name=models.CharField(max_length=200, db_index=True),
slug=models.SlugField(max_length=200, db_index=True),
description=models.TextField(blank=True),
)
category = models.ForeignKey(Category,
related_name='products',
on_delete=models.CASCADE)
age_rate = models.ForeignKey(AgeRate, related_name='products_by_age',
on_delete=models.CASCADE,
default='')
image = models.ImageField(upload_to='products/%Y/%m/%d',
blank=True)
price = models.DecimalField(max_digits=10, decimal_places=3)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
# class Meta:
# ordering = ('name',)
# index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('core:product_detail',
args=[self.id, self.slug])
core:url.py
from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
path('', views.core, name='core'),
path('<slug:category_slug>/', views.product_list,
name='product_list_by_category'),
path('<slug:age_rate_slug>/', views.core,
name='product_list_by_age_rate')
]
main:url.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('account.urls')),
path('', include('core.urls', namespace='core')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def core(request, age_rate_slug=None):
age_rate = None
age_rates = AgeRate.objects.all()
products_by_age = Product.objects.filter(available=True)
if age_rate_slug:
language = request.LANGUAGE_CODE
age_rate = get_object_or_404(AgeRate,
translations__language_code=language,
translations__slug=age_rate_slug)
products_by_age = products_by_age.filter(age_rate=age_rate)
if request.method == 'POST':
if 'send_msg' in request.POST:
# contact_us(request)
form = ContactForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Profile updated successfully')
return redirect(reverse_lazy('core:core'))
else:
return HttpResponse('form is invalid')
else:
return HttpResponse('send_msg didn\'t work')
else:
form = ContactForm()
return render(request, 'core/core.html',
{'form': form,
'products_by_age': products_by_age,
'age_rate': age_rate,
'age_rates': age_rates})
def product_list(request, category_slug=None):
# We use an optional category_slug parameter to
# optionally filter products by a given category.
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
language = request.LANGUAGE_CODE
# Translate category
category = get_object_or_404(Category,
translations__language_code=language,
translations__slug=category_slug)
products = products.filter(category=category)
return render(request,
'core/core.html',
{'category': category,
'categories': categories,
'products': products})
模板
{% load static %}
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ستاره کوچولو</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Bootstrap -->
<link rel="stylesheet" type="text/css" href="{% static "core/css/bootstrap.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "core/fonts/font-awesome/css/font-awesome.css" %}">
<!-- Stylesheet
================================================== -->
<link rel="stylesheet" type="text/css" href="{% static "core/css/style.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "core/css/nivo-lightbox/nivo-lightbox.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "core/css/nivo-lightbox/default.css" %}">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,800,600,300' rel='stylesheet' type='text/css'>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<!-- Navigation
==========================================-->
<nav id="menu" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
<a class="navbar-brand page-scroll" href="#page-top"><i class="fa fa-play fa-rotate-270"></i> # </a> </div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="#page-top" class="page-scroll">خانه</a></li>
<li><a href="#about" class="page-scroll">درباره ما</a></li>
<li><a href="#portfolio" class="page-scroll">محصولات</a></li>
<li><a href="#contact" class="page-scroll">ارتبا با ما</a></li>
<li><a href="index.html" class="page-scroll">ورود</a></li>
<li><a href="index.html" class="page-scroll">ثبت نام</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<!-- Header -->
<header id="header">
<div class="intro">
<div class="container">
<div class="row">
<div class="intro-text">
<h1>#</h1>
<p># </p>
<a href="#about" class="btn btn-custom btn-lg page-scroll">سفارش محصول</a> </div>
</div>
</div>
</div>
</header>
<!-- About Section -->
<div id="about">
<div class="container">
<div class="section-title text-center center">
<h2>درباره ما</h2>
<hr>
</div>
<div class="row">
<div class="col-xs-12 col-md-6"> <img src="{% static "core/img/about.jpg" %}" class="img-responsive" alt=""> </div>
<div class="col-xs-12 col-md-6">
<div class="about-text">
<p># </p>
<p> # </p>
<a href="#portfolio" class="btn btn-default btn-lg page-scroll">محصولات</a> </div>
</div>
</div>
</div>
</div>
<!-- Portfolio Section -->
<div id="portfolio">
<div class="container">
<div class="section-title text-center center">
<h2>محصولات</h2>
<hr>
</div>
<div class="categories">
<ul class="cat">
<li>
<ol class="type">
<li style="margin-bottom: 25px;"><a href="{% url "core:core" %}" data-filter="*" class="active">ALL</a></li>
{% for p in product_by_age %}
<li style="margin-bottom: 25px;">
<a href="{{ p.age_rate.get_absolute_url }}" data-filter=".product"> Age rate {{ p.age_rate }}</a>
</li>
{% endfor %}
<li style="direction:rtl;"><input type="text" class="form-control" id="search"></li>
<li style="margin-left: 30px;"><a href="#"><button class="search-btn">جستجو</button></a></li>
</ol>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="row">
<div class="portfolio-items">
{% for product in products %}
<div class="col-sm-6 col-md-3 col-lg-3 web">
<div class="portfolio-item">
<div class="hover-bg"> <a href="{% static "core/img/portfolio/01-large.jpg" %}" title="Project Title" data-lightbox-gallery="gallery1">
<div class="hover-text">
<h4>{% if category %}{{ category.name }}{% else %}محصولات{% endif %}</h4>
</div>
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "core/img/no_image.png" %}{% endif %}" class="img-responsive" alt="Project Title"></a></div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
<!-- Contact Section -->
<div id="contact" class="text-center">
<div class="container">
<div class="section-title center">
<h2>ارتباط با ما</h2>
<hr>
</div>
<div class="col-md-8 col-md-offset-2">
<form name="sentMessage" action="{% url "core:core" %}" method="post" id="contactForm" novalidate>
{% csrf_token %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<div class="row">
<div class="col-md-6">
<div style="direction: rtl" class="form-group">
<input type="email" name="email" id="email" class="form-control" placeholder="ایمیل" required="required">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div style="direction: rtl" class="form-group">
<input type="text" id="name" name="name" class="form-control" placeholder="نام" required="required">
<p class="help-block text-danger"></p>
</div>
</div>
</div>
<div style="direction: rtl" class="form-group">
<textarea name="message" id="message" class="form-control" rows="4" placeholder="پیام" required></textarea>
<p class="help-block text-danger"></p>
</div>
<div id="success"></div>
<button type="submit" name="send_msg" class="btn btn-default btn-lg">ارسال پیام</button>
</form>
<div class="social">
<ul>
<li><a href="#"><i class="fa fa-phone"><span> تلفن </span></i></a></li>
<li><a href="#"><i class="fa fa-telegram" aria-hidden="true"><span> تلگرام </span></i></a></li>
<li><a href="#"><i class="fa fa-instagram"><span> اینستاگرام </span></i></a></li>
<li><a href="#"><i class="fa fa-whatsapp"><span> واتس آپ </span></i></a></li>
</ul>
</div>
</div>
</div>
</div>
<div id="footer">
<div class="container text-center">
<div class="fnav">
<p> # </p>
</div>
</div>
</div>
<script type="text/javascript" src="{% static "core/js/jquery.1.11.1.js" %}"></script>
<script type="text/javascript" src="{% static "core/js/bootstrap.js" %}"></script>
<script type="text/javascript" src="{% static "core/js/SmoothScroll.js" %}"></script>
<script type="text/javascript" src="{% static "core/js/nivo-lightbox.js" %}"></script>
<script type="text/javascript" src="{% static "core/js/jquery.isotope.js" %}"></script>
<script type="text/javascript" src="{% static "core/js/jqBootstrapValidation.js" %}"></script>
{#<script type="text/javascript" src="{% static "core/js/contact_me.js" %}"></script>#}
<script type="text/javascript" src="{% static "core/js/main.js" %}"></script>
</body>
</html>
模板仅显示: 年龄A-年龄B-以及... 它没有显示任何具有年龄比率类别的产品。
更新:
模板中有两个重要部分: 首先,我想在主页上显示基于年龄比率的所有产品,包括A,B和C,这是一种分类,另一方面,我有另一种基于类型的类别模型,我想在Order页面中使用该类别。当我单击主页上的(全部),(年龄率A)或(年龄率B)时,我看不到基于该链接的产品。您可以看到here。 在管理面板中,我有A and B年龄比率,其链接名称正确显示了here。
例如,当我单击(AGE RATE A)链接时,URL是这样的:http://127.0.0.1/a/。
This是管理页面中的Products实例之一,而This是类别实例。
当我向下滚动时,在主页中的第二个有一个联系表格,可以正常工作。
首先,我在视图中使用了product_list函数,以便在一个函数中同时显示年龄和类别,但是由于我想在首页中显示年龄,因此网址应类似于:
urlpatterns = [
path('', views.core, name='core'),
path('', views.product_list, name='product_list'),
# ....
]
那是行不通的,因为两者都指出了相同的网址,因此我将代码嵌入了核心功能内的视图中,并使用该核心功能进行联系。
这就是我所做的全部。
答案 0 :(得分:0)
您需要将products_by_age添加到模板中。像
{% for p in products_by_age %}
...
响应更新
模板中的 product_by_age
应该为products_by_age
另外,您的2个URL模式也需要不同,例如:
path('category/<slug:category_slug>/', views.product_list,
name='product_list_by_category'),
path('age/<slug:age_rate_slug>/', views.core,
name='product_list_by_age_rate')
然后使用http://127.0.0.1/age/a/。否则http://127.0.0.1/a/将与 first 路径匹配,并尝试将'a'用作category_slug。