The loop is actually for the Navigation. Listing Categories and Shops who sells or render services under each category.
Please.. I'm new to Django and Python. And i'm sorry if i'm very slow to getting this things... Thanks
models.py
class ShopCategories(models.Model):
category = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.category
class NewShop(models.Model):
category = models.ForeignKey(ShopCategories)
main_image = models.FileField(null=True, blank=True)
name = models.CharField(max_length=100, unique=True)
tagline = models.CharField(max_length=50, default='Enter tagline here2')
description = models.TextField(default='enter shop description')
shop_image = models.FileField(null=True, blank=True)
views.py
def homepage(request):
return render_to_response('index.html')
def basefile(request):
cat1 = NewShop.objects.filter(category_id=1)
cat2 = NewShop.objects.filter(category_id=2)
cat3 = NewShop.objects.filter(category_id=3)
cat4 = NewShop.objects.filter(category_id=4)
name1 = ShopCategories.objects.filter(id=1)
name2 = ShopCategories.objects.filter(id=2)
name3 = ShopCategories.objects.filter(id=3)
name4 = ShopCategories.objects.filter(id=4)
return render_to_response('base.html', {'Shop_cat1':cat1, 'Shop_cat2':cat2, 'Shop_cat3':cat3,
'Shop_cat4':cat4,'shop_name1':name1, 'shop_name2':name2,
'shop_name3':name3, 'shop_name4':name4})
base.html
<ul class="nav navbar-nav">
<li class="current-menu-item">
<ul class="nav navbar-nav">
<li class="current-menu-item">
ENTOURAGE MALL
</li>
<li class="dropdown pi-mega-fw menu-item-has-children">
SHOPS
<ul class="dropdown-menu">
<li>
<div class="pi-mega-content">
<div class="row">
<div class="col-md-3 pi-mm-col">
<ul class="pi-mm-list">
{% for shop in shop_name1 %}
<li>
<h3> {{ shop }}</h3>
</li>
{% endfor %}
{% for cat in Shop_cat1 %}
<li>{{ cat }}</li>
{% endfor %}
</ul>
</div>
<div class="col-md-3 pi-mm-col">
<ul class="pi-mm-list">
{% for shop in shop_name2 %}
<li>
<h3> {{ shop }}</h3>
</li>
{% endfor %}
{% for cat in Shop_cat2 %}
<li>{{ cat }}</li>
{% endfor %}
</ul>
</div>
<div class="col-md-3 pi-mm-col">
<ul class="pi-mm-list">
{% for shop in shop_name3 %}
<li>
<h3> {{ shop }}</h3>
</li>
{% endfor %}
{% for cat in Shop_cat3 %}
<li>{{ cat }}</li>
{% endfor %}
</ul>
</div>
</div>
</div>
</li>
</ul>
</li>
<li class="menu-item">
ENTOURAGE LOUNGE
</li>
<li class="menu-item">
About MALL
</li>
<li class="menu-item">
BLOG
</li>
</ul>
index.html
{% extends "base.html" %}
{% block title %} This is Homepage {% endblock title %}
Urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.homepage),
url(r'^base/', views.basefile)
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, docuemt_root= settings.MEDIA_ROOT)
It works just fine in base.html. But when i {% extends base.html %} in index or other templates. The templates loads just fine, but the FOR loop isnt functional. What exactly am i doing wrong?
You should provide context in homepage view in the same way as in basefile view:
def homepage(request):
cat1 = NewShop.objects.filter(category_id=1)
cat2 = NewShop.objects.filter(category_id=2)
cat3 = NewShop.objects.filter(category_id=3)
cat4 = NewShop.objects.filter(category_id=4)
name1 = ShopCategories.objects.filter(id=1)
name2 = ShopCategories.objects.filter(id=2)
name3 = ShopCategories.objects.filter(id=3)
name4 = ShopCategories.objects.filter(id=4)
return render_to_response('index.html', {'Shop_cat1':cat1, 'Shop_cat2':cat2, 'Shop_cat3':cat3,
'Shop_cat4':cat4,'shop_name1':name1, 'shop_name2':name2,
'shop_name3':name3, 'shop_name4':name4})
Related
I have a product card in my Django Application, when clicked, adds to cart. I'm using infinite-scroll and django-pagination.
The issue is with the pagination, however. The first page of results works wonderfully with HTMX. However, the second page and all pages beyond does not work on click. Upon inspecting the page, the html does appear to be rendered properly and I can see the hx-get call with the proper url. But upon clicking, nothing happens.
Maybe I'm missing something obvious here, but any help would be appreciated!
HTML
<div class="container"
data-infinite-scroll='{ "path": ".pagination__next", "append": ".product-card", "history":"false"}'>
{% block content %}
{% include 'includes/cards.html' %}
{% include 'includes/sidebar.html' %}
{% endblock content %}
</div>
<ul class="pagination mt-50 mb-70">
{% if products.has_previous %}
<li class="page-item"><a class="page-link" href="?page={{ products.previous_page_number }}"><i class="fa fa-angle-left"></i></a></li>
{% endif %}
<li class="page-item"><a class="page-link" href="#">{{ products.number }}</a></li>
{% if products.has_next %}
<li class="page-item"><a class="pagination__next" href="?page={{ products.next_page_number }}"><i class="fa fa-angle-right"></i></a></li>
{% endif %}
</ul>
views.py
def shop(request):
anabanner = AnaBanner.objects.all()
gender = Gender.objects.all()
categories = Category.objects.all()
colors = Color.objects.all()
materials = Material.objects.all()
query = request.GET.get('query','')
products = Product.objects.all().order_by('-pk')
if query:
products = products.filter(
Q(name__icontains=query)|
Q(sub_name__icontains=query)
).distinct()
paginator = Paginator(products, 8)
page = request.GET.get('page')
products = paginator.get_page(page)
context = {'products':products,'categories':categories,'gender':gender,'anabanner':anabanner,'colors':colors,'materials':materials}
return render(request, 'shop.html', context)
Button
<div class="button">
<div class="button-layer"></div>
<button name="ekle"
href ="#"
hx-get="{% url 'add_to_cart' product.id %}"
hx-target="#menu-cart-button"
hx-swap="outerHTML"
class="btn btn-outline-secondary add-btn update-cart">Sepete Ekle</button>
</div>
Here i my Infinite scroll pattern django with HTMX
urls.py
highlights_urls = [
path('<slug:slug>/',
views.highlight_detail,
name='highlight_detail',
),
]
urlpatterns = [
path('highlights/', include(highlights_urls)),
]
views.py
def highlight_detail(request, slug: str):
object: Highlight = get_object_or_404(Highlight, slug=slug)
template_name = 'highlight/highlight-detail.html'
if request.htmx:
template_name = 'highlight/partials/highlight-detail-partial-elements.html'
page_number = request.GET.get('page', default=1)
paginator = Paginator(object.products.all(), settings.PAGINATION_PAGE_SIZE)
page_obj = paginator.get_page(page_number)
context = {
'object': object,
'page_obj': page_obj
}
return TemplateResponse(request, template=template_name, context=context)
highlight-detail.html
<section class="padding-top">
<div class="container">
<header class="section-heading">
<h3 class="section-title">{{ object.name }}</h3>
</header>
<div class="row" hx-indicator=".htmx-indicator">
{% include './partials/highlight-detail-partial-elements.html' %}
</div>
</div> <!-- container end.// -->
highlight-detail-partial-elements.html
{% for product in page_obj %}
<div
{% if forloop.last and page_obj.has_next %}
hx-get="{% url 'highlight_detail' object.slug %}?page={{ page_obj.number|add:1 }}"
hx-trigger="revealed"
hx-swap="afterend"
hx-target="this"
{% endif %}
class="col-6 col-sm-4 col-md-3 col-lg-3 col-xl-3">
{% include 'highlight/includes/product-card.html' with object=product %}
</div>
{% endfor %}
I am getting the following error when, from the list view, I try to access the detail view.
Error screenshot
The odd thing is that some of the detail views work, some not, and I do not understand where is the problem. For example, here's the detail view of the organisation with pk=1
organisation detail view
Organisation model
class Organisation(models.Model):
code = models.CharField(max_length=256, unique=True)
name = models.CharField(max_length=256, null=True)
english_name = models.CharField(max_length=256, null=True)
location = models.CharField(max_length=256, null=True)
country = models.ForeignKey('space_missions.Country',
on_delete=models.SET_NULL, null=True, blank=True)
longitude = models.FloatField(null=True)
latitude = models.FloatField(null=True)
parent_organisation = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
Views
class OrganisationDetail(generic.DetailView):
model = models.Organisation
class OrganisationList(generic.ListView):
model = models.Organisation
organisation_list.html
{% extends 'base.html' %}
{% block content %}
<h1>Organisation List</h1>
{% if organisation_list %}
<ul>
{% for organisation in organisation_list %}
<li>
<a href="{% url 'space_missions:organisation-detail' pk=organisation.pk %}">
{{ organisation.name }}
</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No organisation is stored in the database!</p>
{% endif %}
{% endblock %}
organisation_detail.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h1>{{ organisation.name }}'s details:</h1>
<ul>
<li><strong>Code: </strong> {{ organisation.code }}</li>
<li><strong>English Name: </strong> {{ organisation.english_name }}</li>
<li><strong>Location: </strong> {{ organisation.location }}</li>
<li><strong>Country: </strong>
<a href="{% url 'space_missions:country-detail' pk=organisation.country_id %}">
{{ organisation.country.name }}
</a>
</li>
<li><strong>Longitude: </strong> {{ organisation.longitude }}</li>
<li><strong>Latitude: </strong> {{ organisation.latitude }}</li>
<li>
<strong>Parent organisation: </strong>
<a href="{% url 'space_missions:organisation-detail' pk=organisation.parent_organisation_id %}">
{{ organisation.parent_organisation.name }}
</a>
</li>
</ul>
</div>
{% endblock %}
urls.py
from django.urls import path
from . import views
app_name = 'space_missions'
urlpatterns = [
path('countries/', views.CountryList.as_view(), name='countries'),
path('country/<int:pk>/', views.CountryDetail.as_view(), name='country-detail'),
path('astronauts/', views.AstronautList.as_view(), name='astronauts'),
path('astronaut/<int:pk>/', views.AstronautDetail.as_view(), name='astronaut-detail'),
path('organisations/', views.OrganisationList.as_view(), name='organisations'),
path('organisation/<int:pk>/', views.OrganisationDetail.as_view(), name='organisation-detail'),
path('engines/', views.EngineList.as_view(), name='engines'),
path('engine/<int:pk>/', views.EngineDetail.as_view(), name='engine-detail'),
path('stages/', views.StageList.as_view(), name='stages'),
path('stage/<int:pk>/', views.StageDetail.as_view(), name='stage-detail'),
path('launchvehicles/', views.LaunchVehicleList.as_view(), name='launch-vehicles'),
path('launchvehicle/<int:pk>/', views.LaunchVehicleDetail.as_view(), name='launch-vehicle-detail'),
path('missions/', views.MissionList.as_view(), name='missions'),
path('mission/<int:pk>/', views.MissionDetail.as_view(), name='mission-detail'),
path('selections/', views.SelectionList.as_view(), name='selections'),
path('selection/<int:pk>/', views.SelectionDetail.as_view(), name='selection-detail')
]
When parent_organisation is None then your detail page can not find url of organisation-detail with pk=None
<a href="{% url 'space_missions:organisation-detail' pk=organisation.parent_organisation_id %}">
{{ organisation.parent_organisation.name }}
</a>
Wrap your code with if block
{% if organisation.parent_organisation_id %}
<a href="{% url 'space_missions:organisation-detail' pk=organisation.parent_organisation_id %}">
{{ organisation.parent_organisation.name }}
</a>
{% endif %}
I'm new with programming, my mentor only youtube, and when i got error, i search similar error in stackoverflow, but no luck now.
I have a problem with my code or maybe my logic. I don't have much experience or knowledge about call queryset for filtering correctly.
This my urls.py
urlpatterns = [
path('', IndexView.as_view(), name='index'),
path('product/<int:page>', ProductListView.as_view(), name='allproducts'),
path('<categories>/<int:page>', ProductCategoryListView.as_view(),
name='product_category'),
]
I have ProductListView with no error pagination.
class ProductListView(ListView):
context_object_name = 'product_list'
template_name = 'product.html'
model = Product
paginate_by = 16
def get_context_data(self, *args, **kwargs):
context = super(ProductListView, self).get_context_data(*args,**kwargs)
context ['catlist'] = Category.objects.all()
return context
when i filter by category, pagination doesn't work. filter by
category work fine, but when paginate_by more than my product, page
error
Reverse for 'product_category' with arguments '('', 2)' not found. 1 pattern(s) tried: ['(?P[^/]+)/(?P[0-9]+)$']\
class ProductCategoryListView(ListView):
context_object_name = 'product_list'
template_name = 'product_list.html'
model = Product
paginate_by = 20
def get_queryset(self):
self.queryset = self.model.objects.filter(category__name=self.kwargs['categories'])
return super().get_queryset()
def get_context_data(self, *args, **kwargs):
context = super(ProductCategoryListView, self).get_context_data(*args,**kwargs)
context ['catlist'] = Category.objects.all()
return context
This my models.py
class Category(models.Model):
name = models.CharField(max_length=125)
image = models.ImageField(upload_to=upload_location)
class Product(models.Model):
name = models.CharField(max_length=125)
category = models.ForeignKey(Category, null=True, on_delete=models.DO_NOTHING)
image = models.ImageField(upload_to=upload_lokasi)
slug = models.SlugField(blank=True, editable=False)
active = models.BooleanField(default=True)
This my template for ProductCategoryListView
<div class="...">
<div class="...">
<a href="{% url 'products:allproducts' 1%}"...>
All Products
</a>
{% for cat in catlist %}
<a href="{% url 'products:product_category' cat.name 1 %}"...>
{{ cat.name }}
</a>
{% endfor %}
<!-- Product List -->
<div class="row isotope-grid">
{% for prods in product_list %}
<div class="...">
<div class="...">
<div class="...">
<img src="{{ prods.image.url }}" alt="IMG-PRODUCT">
<a href="../{{ prods.slug }}" class="...">
Quick View
</a>
</div>
<div class="...">
<div class="...">
<a href="product-detail.html" class="...">
{{ prods.name }}
</a>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<!-- Pagination -->
<div class="row">
<div class="col-md-8">
{% if is_paginated %}
<nav aria-label="productPage">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="{% url 'products:product_category' category page_obj.previous_page_number %}">Previous</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1" aria-disabled="true">Previous</a>
</li>
{% endif %}
{% for page in paginator.page_range %}
{% if page is page_obj.number %}
<li class="page-item active" aria-current="page">
<span class="page-link" href="#">{{page}}<span class="sr-only">(current)</span></span>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="{% url 'products:product_category' category page %}">{{page}}</a>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="{% url 'products:product_category' category page_obj.next_page_number %}">Next</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1" aria-disabled="true">Next</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
</div>
I guess error comes from here cause logic use different models.
def get_context_data(self, *args, **kwargs):
context = super(ProductCategoryListView, self).get_context_data(*args,**kwargs)
context ['catlist'] = Category.objects.all()
return context
my template
{% for cat in catlist %}
<a href="{% url 'products:product_category' cat.name 1 %}"...>
{{ cat.name }}
</a>
{% endfor %}
I use Category.objects.all() because i don't know how to List
Category from product, just for a name of category can be access.
I hope you guys understand what i asking about.
Sorry for my bad english.
I'm trying to filter children by its parent in my templates. Example being I have houses that are displayed and want to display their amenities(children) along with them. When I try and do so each house list all amenities for every house. How would I make is so that I list a house and only its amenities?
Here are my models:
class Home(models.Model):
name = models.CharField(max_length=255)
photo = models.ImageField()
def __str__(self):
return self.name
class Amenities(models.Model):
home = models.ForeignKey(Home)
amenities = models.CharField(max_length=255)
In my views I am trying to filter the child by its parent:
def index(request):
home = Home.objects.filter()
amenities = Amenities.objects.filter(home=home)
return render(request, 'home/home.html', {'home': home, 'amenities': amenities})
In my template I am try and loop through each home and their amenities like so:
{% for house in home %}
<div class="row">
<div class="col-md-6 portfolio-item">
<a href="house1.html">
<img class="img-responsive" src=" media/{{ house.photo }}" alt="">
</a>
<h3>
House
</h3>
<ul>
{% for i in amenities %}
<li>{{ i.amenities }}</li>
{% endfor %}
</ul>
</div>
</div>
{% endfor %}
thank you
I think you are looking for this
{% for house in home %}
<div class="row">
<div class="col-md-6 portfolio-item">
<a href="house1.html">
<img class="img-responsive" src=" media/{{ house.photo }}" alt="">
</a>
<h3>
House
</h3>
<ul>
{% for i in house.amenities_set.all %}
<li>{{ i.amenities }}</li>
{% endfor %}
</ul>
</div>
</div>
{% endfor %}
my template receives a variable called categories, and I want to list the categories that are "sons" of its father categories
this is my code in template
{% for category,structure in categories|tree_info %}
{% if structure.new_level %}
<li>{{ category.name }} </li>
{% endif %}
{% for level in structure.closed_levels %}
<li>{{level.name}}
{% endfor %}
<ul class="noJS">
{% for cat in category.get_children|tree_info %}
<li>{{ cat.name }}aa </li>
{% endfor %}
</ul>
{% endfor %}
this is the model
class Category(MPTTModel):
name = models.CharField(max_length=50, unique=True)
description = models.TextField(blank=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
def __unicode__(self):
return self.name
any idea?
This worked
{% for category in categories %}
<li>
{{ category.name }}
<ul class="noJS">
{% for cat in category.get_children %}
<li>{{ cat.name }} </li>
{% endfor %}
</ul>
</li>
{% endfor %}