Django NoReverMatch at / - python

I read the book 'Django By Example' and run the examples in chaper7.
But the results call "NoReverMatch at /"
NoReverseMatch at /
Reverse for 'product_detail' with arguments '(5, u'ironman')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<id>[\\d+])/(?P<slug>[-\\w+])/$']
This is the 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)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_list_by_category', args=[self.slug])
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail', args=[self.id, self.slug])
This is the urls.py
urlpatterns = [
url(r'^$', views.product_list, name='product_list'),
url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'),
url(r'^(?P<id>\d+)/(?P<slug>[-\w+])/$', views.product_detail, name='product_detail'),
]
This is the 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})
def product_detail(request, id, slug):
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
return render(request, 'shop/product/detail.html', {'product': product})
And this is the 'list.html' template where the error occurs.
{% extends "shop/base.html" %}
{% load static %}
{% block title %}
{% if category %}{{ category.name }}{% else %}Products{% endif %}
{% endblock %}
{% block content %}
<div id="sidebar">
<h3>Categories</h3>
<ul>
<li {% if not category %} class="selected" {% endif %}>
All
</li>
{% for c in categories %}
<li {% if category.slug == c.slug %} class="selected" {% endif %}>
{{ c.name }}
</li>
{% endfor %}
</ul>
</div>
<div id="main" class="product-list">
<h1>{% if category %}{{ category.name }}{% else %}Products{% endif %} </h1>
{% for product in products %}
<div class="item">
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static 'img/no_image.png' %}{% endif %}">
</a>
{{ product.name }}<br>
${{ product.price }}
</div>
{% endfor %}
</div>
{% endblock %}
The error occurs at
<a href="{{ product.get_absolute_url }}">
-- line.
Why this error occurs??

It looks to me like you need to change your url pattern:
url(r'^(?P<id>\d+)/(?P<slug>[-\w+])/$', views.product_detail, name='product_detail')
perhaps to:
url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail')
'+' does not function as a special character inside square brackets, so [-\w+] will only match a single character (alphanumeric or '-'), but you are passing multi-character strings like 'ironman'. [-\w]+ will match one or more characters.

Related

get_object_or_404() got an unexpected keyword argument 'slug'

TypeError at /vegetables/
get_object_or_404() got an unexpected keyword argument 'slug'
views.py
from django.shortcuts import render, get_object_or_404
from .models import Category
from .models import Product
def allProductCategory(request,c_slug=None):
c_page=None
products=None
if c_slug!=None:
c_page=get_object_or_404(Category,slug=c_slug)
products=Product.objects.all().filter(category=c_page,available=True)
else:
products=Product.objects.all().filter(available=True)
return render(request, 'category.html',{'category':c_page,'products':products})
urls.py
app_name='ecommerceapp'
urlpatterns = [
path('',views.allProductCategory,name='allProductCategory'),
path('<slug:c_slug>/',views.allProductCategory,name='products_by_category'),
]
Includes 2 tables-Category, Product
models.py
class Category(models.Model):
name = models.CharField(max_length=250,unique=True)
slug = models.SlugField(max_length=250,unique=True)
desc = models.TextField(blank=True)
image = models.ImageField(upload_to='category',blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return '{}'.format(self.name)
def get_url(self):
return reverse('ecommerceapp:products_by_category',args=[self.slug,])
class Product(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
desc = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
image = models.ImageField(upload_to='product', blank=True)
stock = models.IntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def __str__(self):
return '{}'.format(self.name)
Base.html is created. header.html, navbar.html, footer.html are included in base.html. Other than these three a block content and endblock is created in base.html.
category.html
{% extends 'base.html' %}
{% load static %}
{% block metadescription %}
{% if category %}
{{ category.description|truncatewords:155 }}
{% else %}
Welcome to ZUPER Store where you can get everything.
{% endif %}
{% endblock %}
{% block title %}
{% if category %}
{{ category.name }} - ZUPER store
{% else %}
All that you need - ZUPER store
{% endif %}
{% endblock %}
{% block content %}
{% if category %}
<div>
<div>
<p>Our products</p>
</div>
</div>
{% endif %}
<div>
{% if category %}
<img src="{{category.image.url}}" alt="{{category.name}}">
</div>
<br>
<div>
<h1>{{category.name}}</h1>
<p>{{category.description}}</p>
</div>
{% else %}
<div>
<img src="{% static 'images/Banner.png' %}" alt="Our products" width="500px;" height="100px;">
</div>
<br>
<div>
<h1>Our product collections</h1>
<p>Dummy content</p>
</div>
{% endif %}
<div>
<div>
{% for product in products %}
<div>
<div>
<img src="{{product.image.url}}" alt="{{product.name}}">
<div>
<h4>{{product.name}}</h4>
<p>{{product.price}}</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
I'am getting this error when I click on the hyperlink vegetables and cotton dress.

Cant get data from view to django template

Problem as in title. I can not get data from view to template I get <QuerySet [{'id': 3, 'order_user_id': 13, 'ordered': False, 'total': Decimal('0.00')}]> when i use
{{ order }}. I would like to get OrderedItems and Total from Order Model. How can i do that?
views.py
def cart(request):
order = Order.objects.values()
context = {'order': order}
return render(request, 'shop/cart.html', context)
models.py:
class OrderItem(models.Model):
order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True)
quantity = models.IntegerField(default=1)
class Order(models.Model):
order_user = models.OneToOneField(User, on_delete=CASCADE)
order_items = models.ManyToManyField(OrderItem)
ordered = models.BooleanField(default=False)
total = models.DecimalField(default=0.00, decimal_places=2, max_digits=11)
class Item(models.Model):
title = models.CharField(max_length=150)
price = MoneyField(
decimal_places=2,
default=0,
default_currency='USD',
max_digits=11,
)
cart.html
{% extends 'shop/base.html' %}
{% block content %}
<div class="container">
{% include 'shop/navbar.html' %}
<div>
{{order}}
{{order.total}}
</div>
</div>
{% endblock content %}
You have to use for loop to iterate over the items.
First, change this: order = Order.objects.values() to order = Order.objects.all()
{% extends 'shop/base.html' %}
{% block content %}
<div class="container">
{% include 'shop/navbar.html' %}
<div>
{% for item in order %}
<li>User: {{ item.order_user }}<li/>
<li>Items:
{% for order_item in item.order_items %}
<li>{{ order_item }}</li>
{% endfor %}
<li/>
<li>Is ordered: {{ item.ordered }}<li/>
<li>Total: {{ item.total }}<li/>
{% endfor %}
</div>
</div>
{% endblock content %}

account/list_of_post_by_subactegory.html TemplateDoesNotExist

I can't solve this problem. When you try to load the page, list_of_post_by_subcategory.html throws TemplatesDoesNotExist, Please help.
models.py
class Category(models.Model):
category = models.CharField(max_length=250)
slug = models.SlugField()
def __str__(self):
return self.category
def get_absolute_url(self):
return reverse('list_of_post_by_category', args=[self.slug])
class SubCategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name="subcategories")
subcategory = models.CharField(max_length=250)
slug = models.SlugField()
def __str__(self):
return self.subcategory
def get_absolute_url(self):
return reverse('list_of_post_by_subcategory', args=[self.slug])
urls.py
url(r'^category/(?P<slug>[-\w]+)/$', views.list_of_post_by_category, name= 'list_of_post_by_category'),
url(r'^subcategory/(?P<slug>[-\w]+)/$', views.list_of_post_by_subcategory, name= 'list_of_post_by_subcategory'),
views.py
def list_of_post_by_category(request, slug):
categories = Category.objects.all()
category=get_object_or_404(Category, slug = slug)
subcategories = SubCategory.objects.filter(category=category)
posts = Post.objects.filter(category=category)
return render(request, "account/list_of_post_by_category.html", {'categories': categories, 'posts': posts, 'category': category, 'subcategories': subcategories})
def list_of_post_by_subcategory(request, slug):
subcategory=get_object_or_404(SubCategory, slug=slug)
posts = Post.objects.filter(subcategory=subcategory)
return render(request, "account/list_of_post_by_subcategory.html", {'posts': posts, 'subcategory': subcategory})
list_of_post_by_subcategory.html
{% extends "base.html" %}
{% block title %}{{ subcategory.subcategory }}{% endblock %}
{% block content %}
<h1>{{ subcategory.subcategory }}</h1>
{% for post in posts %}
<div class="single_post">
{{ post.title }}
<br/>
<br/>
<div>
{{ post.publish }}
{{ post.subcategory }}
</div>
</div>
{% endfor %}
<br/>
{% endblock %}
Similar template list_of_post_by_category.html loads correctly. But list_of_post_by_subcategory.html throws TemplateDoesNotExist.
The filenames don't match here. You posted your error as account/list_of_post_by_subactegory.html TemplateDoesNotExist Look at the name of html file you mentioned(subactegory). And the one you are calling has this name account/list_of_post_by_subcategory.html

Django: List Products of each Categories in a page

I have a few categories and I would like to list the products per category in the format below (categories is an FK to products):
Category 1
bunch of products
....
Category N
bunch of products
I have tried many ways but so far I only get the categories but not the products to show in my HTML.
models.py
class Category(models.Model):
title = models.CharField(max_length=225)
slug = models.SlugField(unique=True, blank=True, null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('category_detail', kwargs={'slug': self.slug})
#property
def get_products(self):
return Products.objects.filter(category=self.title)
class Products(models.Model):
title = models.CharField(max_length=225)
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
blank=True, on_delete=models.CASCADE)
categories = models.ForeignKey(Category, related_name='Category', blank=True, on_delete=models.CASCADE) #this
gender = models.CharField(max_length=20, choices=GENDER_CHOICES, default="male")
objects = ProductManager()
def get_absolute_url(self):
return reverse('product_detail', args=(self.id,))
def __str__(self):
return self.title
views.py
def categories_m(request):
query_Set = models.Category.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(query_Set, 20)
try:
cat = paginator.page(page)
except PageNotAnInteger:
cat = paginator.page(1)
except EmptyPage:
cat = paginator.page(paginator.num_pages)
return render(request, 'products/categories.html', {'categories': cat})
html
{% extends 'base.html' %}
{% block content %}
{% for category in categories %}
<h1>{{ category }}</h1>
{% for product in categories.get_products %}
<p>{{ product }}</p>
{% endfor %}
{% endfor %}
{% endblock %}
It should be category instead of categories in your template. And in your model filter products by category title.
#property
def get_products(self):
return Products.objects.filter(categories__title=self.title)
{% extends 'base.html' %}
{% block content %}
{% for category in categories %}
<h1> {{category}} </h1>
{% for product in category.get_products %}
<p> {{product}} </p>
{% endfor %}
{% endfor %}
{% endblock %}
You could remove the related_name attribute from your field
class Products(models.Model):
categories = models.ForeignKey(Category, blank=True, on_delete=models.CASCADE)
And then in your template you can use category.products_set.all
{% extends 'base.html' %}
{% block content %}
{% for category in categories %}
<h1>{{ category }}</h1>
{% for product in category.products_set.all %}
<p>{{ product }}</p>
{% endfor %}
{% endfor %}
{% endblock %}

Django post not showing on homepage, but in category list

I made a blog with Django. The blog lets the admin create posts and categories. I used bootstrap to align the posts next to each other.
This is the homepage of my blog. When the posts reach the other end of the screen. look at the Example below:
post1 post2 post3 post4 post5 post6 post7 post8 post9 post10 post11 post12 post 13 post14 post16.
post 16 wouldnot show on the homepage, but if you go to its category it will show on the category list but not on the homepage which is index.html
index.html
{% extends 'base.html' %}
{% block content %}
{% if categories %}
<div class="tab">
{% for category in categories %}
<button class="tablinks"><a href="{{ category.get_absolute_url }}">{{
category.title }}</a></button>
{% endfor %}
{% else %}
<p>There are no posts.</p>
{% endif %}
</div>
<br><br><br>
<div class="container ">
{% if posts %}
<div class="row ">
{% for post in posts %}
<div class="poosts col-md-2">
<p class="past"><a class="link" href="{{ post.get_absolute_url }}"><span
class="tda"> {{post.title}}</span><br><br><span class="postbody">
{{post.body|truncatewords:13}}</a></span></p>
</div>
{% endfor %}
{% else %}
<p class="text-center">There are no posts.</p>
</div>
{% endif %}
</div>
{% endblock %}
categories page
{% extends 'base.html' %}
{% block head_title %}Viewing category {{ category.title }}{% endblock %}
{% block title %}{{ category.title }}{% endblock %}
{% block content %}
<br><br><br>
<div class="container">
{% if posts %}
<div class="row">
{% for post in posts %}
<div class="poosts col-md-4">
<p class="past"><a class="link" href="{{ post.get_absolute_url }}"><span
class="tda"> {{post.title}}</span><br><br>{{post.body|truncatewords:13}}</a>
</p>
</div>
{% endfor %}
{% else %}
<p class="text-center">There are no posts.</p>
</div>
{% endif %}
</div>
{% endblock %}
views.py
from django.shortcuts import render, redirect, get_list_or_404
from django.http import HttpResponse
from .models import Blog, Category
from django.shortcuts import render_to_response, get_object_or_404
def index(request):
return render_to_response('account/index.html', {
'categories': Category.objects.all(),
'posts': Blog.objects.all()[:5]
})
def view_post(request, slug):
return render_to_response('account/view_post.html', {
'post': get_object_or_404(Blog, slug=slug)
})
def view_category(request, slug):
category = get_object_or_404(Category, slug=slug)
return render_to_response('account/view_category.html', {
'category': category,
'posts': Blog.objects.filter(category=category)[:5]
})
models.py
from django.db import models
from django.db.models import permalink
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
body = models.TextField()
posted = models.DateTimeField(db_index=True, auto_now_add=True)
category = models.ForeignKey('Category')
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_blog_post', None, { 'slug': self.slug })
def __str__(self):
return self.title
class Category(models.Model):
title = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_blog_category', None, { 'slug': self.slug })
def __str__(self):
return self.title
you should try this 'posts': Blog.objects.all() in views.py

Categories