Django view function for navbar included - django

I have my page only for navigation bar and I include it in base page. Now I have a menu in that navigation bar and links I get from database(that links are my categories).
But how can I call my function in views without path, because I don't need to have path for navigation bar? And I need that view function to get data from database.
models.py
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
info = models.TextField(default="Informacion a Completar")
image = models.ImageField(blank=True)
views.py
def CategoryView(request):
context = {
'items' : Item.objects.all()
}
return render(request, 'categories_bar.html', context=context)
categories_bar.html
<li class="nav-item"></li>
{% for category in items %}
<div> {{ category.category }} </div>
{% endfor %}
</li>
base.html
{% include "categories_bar.html" %}

You can use block tags like this:
base.html:
<nav>
<ul>
{% block categories %}{% endblock %}
</ul>
</nav>
<!-- replace navbar code with yours -->
categories_bar.html:
{% block categories %}
{% for category in items %}
<li class="nav-item"></li>
<div> {{ category.category }} </div>
</li>
{% endfor %}
{% endblock %}

Related

Reverse for 'allproduct' not found. 'allproduct' is not a valid view function or pattern name

urls.py
from django.urls import path
from . import views
app_name='shop'
urlpatterns = [
path('',views.allproduct,name='allproductcat'),
path('<slug:c_slug>/',views.allproduct,name='product_by_catagory')
]
views.py
from django.shortcuts import render, get_object_or_404
from . models import catagory,product
# Create your views here.
def allproduct(request,c_slug=None):
c_page=None
products=None
if c_slug!=None:
c_page=get_object_or_404(catagory,slug=c_slug)
products=product.objects.all().filter(catagory=c_page,available=True)
else:
products=product.objects.all().filter(available=True)
return render(request,'catagory.html',{'catagory':c_page,'products':products})
model.py
from django.db import models
# Create your models here.
from django.urls import reverse
class catagory(models.Model):
name=models.CharField(max_length=250,unique=True)
slug=models.SlugField(max_length=250,unique=True)
description=models.TextField(blank=True)
image=models.ImageField(upload_to='catagory',blank=True)
class Meta:
ordering=('name',)
verbose_name='catagory'
verbose_name_plural='catagories'
def __str__(self):
return '{}'.format(self.name)
def get_url(self):
return reverse('shop:product_by_catagory',args=(self.slug,))
class product(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
image = models.ImageField(upload_to='product', blank=True)
price=models.DecimalField(max_digits=10,decimal_places=2)
stock=models.IntegerField()
available=models.BooleanField()
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
catagory=models.ForeignKey(catagory,on_delete=models.CASCADE)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def __str__(self):
return '{}'.format(self.name)
catagory. html
{% extends 'base.html' %}
{% load static %}
{% block metadiscription %}
{% if catagory %}
{{catagory.discription}}
{% else %}
welcome
{% endif %}
{% endblock %}
{% block title %}
{% if catagory %}
{{catagory.name}}--ABC store
{% else %}
see our new collection
{% endif %}
{% endblock %}
{% block content %}
{% if catagory %}
<div>
<div>
OUR PRODUCT COLLECTION
</div>
</div>
{% endif %}
<div>
{% if catagory %}
<img src="{{catagory.img.url}}" alt="{{catagory.name}}">
</div>
<br>
<div>
<h1>
{{catagory.name}}
</h1>
<p>
{{catagory.discription}}
</p>
</div>
{% else %}
<div>
<img src="{% static 'img/banner.png' %}">
</div>
<br>
<div>
<h1>OUR PRODUCT COLLECTION</h1>
<p>INDIA IS MY COUNTRY I LOVE MY COUNTRY</p>
</div>
{% endif %}
<div>
<div>
{% for product in products %}
<div>
<div>
<div>
<h4>{{product.name}}</h4>
<p>{{product.price}}</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
context_processors.py
from . models import catagory
def menu_link(request):
link=catagory.objects.all()
return dict(links=link)
i can't load the catagory page using the slug address,that is dress, when i enter that it is showing there is no revrse for allproducts, and when i open the website there is no image in image position.as i have uploaded the image file in the admin pannel
The name=… of your path is allproductcat, not allproduct, you thus should implement a link with:
OUR PRODUCT COLLECTION

How to display a list of posts in a list of categories in Django

I am looking for my web page to display a list of categories and a list of each post within the category.
For example:
However, it is looping through and displaying each category and associated post separately, like this:
Here is Template:
<ul>
{% for p in object_list %}
<li>
{{p.category.name}}
<ul>
<li>
{{p.title}}
</li>
</ul>
</li>
{% endfor %}
</ul>
Model
class Category(models.Model):
name = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category', null=False)
Views
class CategoryList(ListView):
template_name = 'category_list.html'
def get_queryset(self):
return Post.objects.all().select_related('category')
Try changing your template code to this
{% regroup object_list by category as post_list %}
<ul>
{% for post_category in post_list %}
<li>{{ post_category.grouper }}
<ul>
{% for post in post_category.list %}
<li>{{ post.title }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
try this:
views.py:
def get_queryset(request):
categorys = {category: Post.objects.filter(category = category) for category in Category.objects.all()}
Template:
<ul>
{% for category, posts in categorys.items %}
<li>
{{category.name}}
{% for comment in comments %}
<ul>
<li>
{{posts.title}}
</li>
</ul>
{% endfor %}
<li>
{% endfor %}
</ul>
Use 2-layer nested loops to display posts and categories, each item in the outer loop is a category, and each item category in the inner loop is the title of the posts.
You can do that in the template with regroup. Also order the items to be grouped by the field you wish to group with.
https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#regroup

a post with border and no border using for or if in django

models.py:
class post(models.Model):
title = models.CharField(max_length=40)
picture = models.ImageField(upload_to='somewhere/dir')
active_post = models.BooleanField(default=True)
commercial_post = models.BooleanField(default=False)
normal_post = models.BooleanField(default=True)
post_with_colored_border = models.BooleanField(default=False)
post_title_bold = models.BooleanField(default=False)
post_with_border_and_title_bold = models.BooleanField(default=False)
def __str__ (self):
return self.title
views.py:
def index(request):
posts= post.objects.filter(active_post=True)
normal_post = posts.filter(normal_post=True)
commercial_post = posts.filter(commercial_post=True)
post_with_border = posts.filter(post_with_colored_border=True)
post_title_bold = posts.filter(post_title_bold=True)
post_with_border_and_title_bold = posts.filter(post_with_border_and_title_bold=True)
context = {
'posts':posts,
'commercial_post':commercial_post,
'post_with_border':post_with_border,
'post_title_bold':post_title_bold,
'post_with_border_and_title_bold':post_with_border_and_title_bold,
}
return render(request, 'index.html', context)
index.html:
{% if post_with_border AND commercial_post %}
{% for abc in posts %}
<div>
<a href="#" class="border border-danger">
<img src="{{abc.picture.url}}">
</a>
<h1>
<a href="#" class="SomeClass"> {{abc.title}}
</a>
</h1>
</div>
{% endfor %}
{% else %}
{% for abc in normal_post %}
<div>
<a href="#">
<img src="{{abc.picture.url}}">
</a>
<h6>
<a href="#"> {{abc.title}}
</a>
</h6>
</div>
{% endfor %}
{% endif %}
i want to make it to list if its a commercial post it should have a border and a H1 in title but if its a normal post it should have no border and H6. But the problem is it shows all posts with border and H1.
I need your help please
Thank you
You should consider restructuring your model.
models.py
class post(models.Model):
title = models.CharField(max_length=40)
picture = models.ImageField(upload_to='somewhere/dir')
active_post = models.BooleanField(default=True)
commercial_post = models.BooleanField(default=False)
def __str__ (self):
return self.title
views.py
def index(request):
posts= post.objects.filter(active_post=True)
context = {
'posts':posts,
}
return render(request, 'index.html', context)
index.html
{% for post in posts %}
<div>
{% if post.commercial_post %}
<a href="#" class="border border-danger">
<img src="{{post.picture.url}}">
</a>
<h1>
<a href="#" class="SomeClass"> {{post.title}}
</a>
</h1>
{% else %}
<a href="#">
<img src="{{post.picture.url}}">
</a>
<h6>
<a href="#"> {{post.title}}
</a>
</h6>
{% endif %}
</div>
{% endfor %}
Regards
You're checking whether the post is commercial before you've looped through them, I think what you want is:
{% for post in posts %}
{% if post.commercial_post is True %}
// border & h1 tags, etc.
{% else %
// other stuff
{% endfor %}
I would go further and just use the if statement to set a class on the div, you can then dictate how that particular class is styled in the CSS - this would make your template much cleaner.
Furthermore, if your logic is simply that a commercial post has certain formatting then you should remove all the other fields in your model and from the views.py:
post_with_colored_border = models.BooleanField(default=False)
post_title_bold = models.BooleanField(default=False)
post_with_border_and_title_bold = models.BooleanField(default=False)

How to retrieve the children in Django

I have a model Category like so :
class Category(TimeStampedModel):
category_parent = models.ForeignKey('self', blank=True, null=True)
name = models.CharField(max_length = 200)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
What I want is to display all the categories that do not have parents at first, and then, in nested lists, their respective children : for example :
Flowers
Lilac
Rose
Trees
Maple
So what I have tried is that :
def get_categories(request):
categories = Category.objects.filter(category_parent=None)
return {'categories' : categories}
But when I try to display the children of each category, none appears, following my example, I only get Flowers and Trees..
<ul class="nav-list">
{% for category in categories %}
<li class="nav-item"><a class="nav-link" href="#">{{ category.name }}</a>
{% if category.categories %}
<ul class="nav-submenu">
{% for subcategory in category.categories %}
<li class="nav-submenu-item">{{ subcategory.name }}</li>
{% endfor %}
</ul>
{% endif %}
</li>
{% endfor %}
</ul>
How can I get the children too ?
You didn't specify related name "categories" to the category_parent field so you can't access it via category.categories. You can try using this expression
{% for subcategory in category.category_set.all %}
<!-- subcategory staff -->
{% endfor %}
in your template.

Django-endless-pagination twitter style pagination not working

I am using django-endless-pagination for my project. But its not working as it is supposed to. Neither is it showing the show more or neither does it work when I change the code to onscroll mode.
<script>$.endlessPaginate({paginateOnScroll: true});</script>
However the include tags are working as its showing the snaps in the template. And even both the scripts (i.e. the jquery and endless.js) are there. What am I missing? Your help and guidance will be very much appreciated. Thank you.
models.py:
class SnapGroup(models.Model):
name = models.CharField(max_length=150, blank=True, null=True)
date = models.DateField(default=date.today)
class Snap(models.Model):
date = models.ForeignKey(SnapGroup)
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=150, blank=True, null=True)
views.py:
#page_template('snapgroups.html') # just add this decorator
def snaps(
request, template='snaps.html', extra_context=None):
context = {
'snapgroup': SnapGroup.objects.all(),
}
if extra_context is not None:
context.update(extra_context)
return render_to_response(
template, context, context_instance=RequestContext(request))
snaps.html:
{% if snapgroup.count > 0 %}
<div class="endless_page_template">
{% include page_template %}
</div>
{% block js %}
{{ block.super }}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}endless_pagination/js/endless-pagination.js"></script>
<script>$.endlessPaginate();</script>
{% endblock %}
{% else %}
<li><p>No SNAPGROUP yet!</p></li>
<span class="clear_both"></span>
{% endif %}
snapgroups.html:
{% load endless %}
{% paginate snapgroup %}
{% for sg in snapgroup %}
<h4 id="combination" class="snap_date">{{sg.date|date:'l'}}, {{sg.date}}</h4>
<ul>
{% for snap in sg.snap_set.all %}
<li><img src="{{MEDIA_URL}}{{snap.image}}" alt="{{snap.caption}}" /></li>
{% endfor %}
<span class="clear_both"></span>
</ul>
{% endfor %}
{% show_more %}
Solved my problem by this post. Hope this will help someone else.