How to fix NoReverseMatch in django - python

I am developing an ecommerce website just for a practice and all the codes were working fine but all of a sudden I am getting a error at the django template
I have tried following most of the answers but none of it seems to working
This is my urls.py
urlpatterns = [
url(r'^$', views.cart_detail, name='cart_detail'),
url(r'^add/(?P<product_id>\d+)/$', views.cart_add, name='cart_add'),
url(r'^remove/(?P<product_id>\d+)/$', views.cart_remove, name='cart_remove'),
]
this is my main urls.py of the project
urlpatterns = [
# Examples:
# url(r'^$', 'myshop.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^cart/', include('cart.urls', namespace='cart')),
url(r'^orders/', include('orders.urls', namespace='orders')),
url(r'^paypal/', include('paypal.standard.ipn.urls')),
url(r'^payment/', include('payment.urls', namespace='payment')),
url(r'^coupons/', include('coupons.urls', namespace='coupons')),
url(r'^', include('shop.urls', namespace='shop')),
]
this is the template in which I am getting error
{% block content %}
<h1>Your shopping cart</h1>
<table class="cart table-striped ">
<thead>
<tr>
<th>Image</th>
<th>Product</th>
<th>Quantity</th>
<th>Remove</th>
<th>Unit Price</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{% for item in cart %}
{% with product=item.product %}
<tr>
<td>
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}
{{ product.image.url }}
{% else %}{% endif %}">
</a>
</td>
<td>{{product.name}}</td>
<td>
<form action="{% url 'cart:cart_add' product.id %}" method="post">
{{item.update_quantity_form.quantity}}
{{item.update_quantity_form.update}}
<input type="submit" class=" btn btn-default outline" value="update">
{% csrf_token %}
</form>
</td>
<td>
Remove
</td>
<td class="num">${{item.price}}</td>
<td class="num">${{item.total_price}}</td>
</tr>
{% endwith %}
{% endfor %}
{% if cart.coupon %}}
<tr class="subtotal">
<td class="{% trans 'subtotal' %}"></td>
<td colspan="4"></td>
<td class="num">${{ cart.get_total_price}}</td>
</tr>
<tr>
{% blocktrans with code=cart.coupon.code discount=cart.coupon.discount %}
<td>"{{ code}}" coupon ({{ discount}}% off)</td>
{% endblocktrans %}
<td colspan="4"></td>
<td class="num neg">- ${{cart.get_discount|floatformat:"2"}}</td>
</tr>
{% endif %}
<tr class="total"></tr>
<td>{% trans "total" %}</td>
<td colspan="4"></td>
<td class="num">${{ cart.get_total_price_after_discount|floatformat:"2"}}</td>
</tbody>
</table>
<p>
{% trans "Apply for a coupon" %}
</p>
<form action="{% url 'coupons:apply' %}" method="post">
{{ coupon_apply_form}}
<input type="submit" value="{% trans 'Apply' %}">
{% csrf_token %}
</form>
<p class="text-right">
Continue shopping
Checkout
</p>
{% endblock %}
this is the error that I am getting
Error during template rendering
In template /Users/nirvana/PycharmProjects/Ecommerce/myshop/templates/cart/detail.html, error at line 35
Reverse for 'cart_add' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['cart/add/(?P<product_id>\\d+)/$']
25
<tr>
26 <td>
27 <a href="{{ product.get_absolute_url }}">
28 <img src="{% if product.image %}
29 {{ product.image.url }}
30 {% else %}{% endif %}">
31 </a>
32 </td>
33 <td>{{product.name}}</td>
34 <td>
35
<form action="
{% url 'cart:cart_add' product.id %}
" method="post">
36 {{item.update_quantity_form.quantity}}
37 {{item.update_quantity_form.update}}
38 <input type="submit" class=" btn btn-default outline" value="update">
39 {% csrf_token %}
40 </form>
41 </td>
42
<td>
43 Remove
44 </td>
45 <td class="num">${{item.price}}</td>

Related

JInja2 Template Syntax Error Encountered Unknown tag 'endif'

I am building a basic api based website as I was going to display some info om page and was checking for a condition i encountered --
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.
Below is the palatte I copied form Bootstrap and was modifying and then the error happened -- And Yeah This is my first time posting question here as you can tell!
{% include "header.html" %}
{% block contnet %}
<div class="container-fluid">
<div class="row row-dark">
<div class="col px-2 py-5">
<h6 class="px-2 py-3">Click to Know Upcoming Events</h6>
<a href="{{ url_for('upcoming_events') }}"
><button type="button" class="btn btn-dark mx-2 my-3">Events</button></a
>
</div>
</div>
<div class="row">
<div class="col col-lg-4 col-md-6">
<table class="table table-borderless py-5 table-light">
<thead>
<tr class="table-light">
<th scope="col">Batting</th>
<th scope="col">Bowling</th>
<th scope="col">Wickets</th>
<th scope="col">Over</th>
</tr>
</thead>
<tbody>
{% if error %} # <========
<p>{{ error }}</p>
{% endif %} <======= Here is the error traceback
<tr>
<th scope="row"></th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td colspan="2">Larry the Bird</td>
<td>#twitter</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}
You close the "if" twice ({% endif %}) but only open one...
Try this:
Click to Know Upcoming Events Events Batting Bowling Wickets Over
{% if error: %}
{{ error }}
{% endif %}
Mark Otto #mdo 2 Jacob Thornton #fat 3 Larry the Bird #twitter
{% endblock %}
You can move the {% endif %} where you want

Django template for loop is empty in another block

I have a function in my view.py:
#login_required(login_url='login')
def gpd(request,pk):
# get gpd by id
current_gpd = get_gpd(pk)
# get current campaign year #TODO check types
current_campaign = get_campaign(current_gpd.gpd_year)
# get all corporate goals for current campaign
corp_goals = CorporateGoal.objects.filter(gpd_year=current_campaign.year)
compl_weight = []
for goal in corp_goals:
compl_weight.append(goal.corp_factor_weight*current_gpd.bonus.corporate_component//100)
corporate_goals = zip(corp_goals, compl_weight)
if is_manager(request)!=None:
team = get_team(request)
context = {'gpd':current_gpd,
'corporate_goals':corporate_goals,
}
return render(request, 'app/gpd_forms/form_gpd.html', context)
else:
context = {'gpd':current_gpd,
'corporate_goals':corporate_goals,
}
return render(request, 'app/gpd_forms/form_gpd.html', context)
As you can see, in context I have corporate_goal.
My form_gpd.html:
{% extends 'app/navbar/main.html' %}
{% load static %}
{% block content %}
{% include 'app/slidebar/gpd_form_slidebar.html' %}
<div class="container" style="background-color:white">
<div class="row">
<div id="section2" class="container-fluid">
{% include 'app/gpd_blocks/corporate_goal.html' %}
</div>
</div>
<hr />
</div>
<div class="container" style="background-color:white">
<div class="row">
<div id="section5" class="container-fluid">
{% include 'app/gpd_blocks/summary.html' %}
</div>
</div>
<hr />
</div>
</div>
{% endblock %}
for example in corporate block I am executing next:
{% load static %}
{% block content %}
<div class="row" id="super">
<p>&nbsp</p>
</div>
<div class="row" id="super">
<div class="col-11" style="color: ivory; font-weight: bold; font-size: 1.3em;">
CORPORATE GOALS BLOCK
</div>
</div>
<div class="row" id="super">
<p>&nbsp</p>
</div>
{% for goal, compl_weight in corporate_goals %}
<hr style="height:2px;border:none;color:rgb(87, 124, 161);background-color:rgb(87, 124, 161);" />
<!-- Corporate goal section-->
<div class="row">
<div class="col">
Corp. Goal: {{ goal.corp_goal_title }}
</div>
</div>
<div class="row">
<div class="col-8">
<div>
{% if goal.corp_factor_rate %}
<p style="color:mediumspringgreen">rated</p>
{% else %}
<p style="color:indianred">unrated</p>
{% endif %}
</div>
</div>
<div class="col-3">
<div style="margin-inline-start:auto">
{{compl_weight}} % of total score
</div>
</div>
</div>
<!-- Tabs for details-->
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" href="#det1{{ goal.id }}">Goal Details</a></li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#det2{{ goal.id }}">Other Details</a></li>
</ul>
<!-- Tabs content for details-->
<div class="tab-content" >
<!--First tab-->
<div id="det1{{ goal.id }}" class="tab-pane fade show active">
<div class="row">
<!--Column 1-->
<div class="col">
<table class="table-bordless" style="margin-top:20px;">
<tbody>
<tr>
<th>Start Date</th>
<td width="50"></td>
<td>{{ goal.start_date }}</td>
</tr>
<tr>
<th>Weight</th>
<td width="20"></td>
<td>{{ goal.corp_factor_weight }} %</td>
</tr>
<tr>
<th><p>&nbsp</p></th>
</tr>
<tr>
<th style="color:dimgray">Goal description</th>
<td width="18"></td>
<td></td>
</tr>
</tbody>
</table>
<div class="row">
<textarea class="form-control" readonly title="Description" style="background-color:aliceblue !important;">{{goal.corp_goal_description}}</textarea>
</div>
</div>
<!--Column 2-->
<div class="col">
<table class="table-bordless" style="margin-top:20px;">
<tbody>
<tr>
<th>Due Date</th>
<td width="50"></td>
<td>{{ goal.end_date }}</td>
</tr>
<tr>
<th>Factor Rate</th>
<td width="50"></td>
<td>
{% if goal.corp_factor_rate %}
{{ goal.corp_factor_rate }}
{% else %}
<div style="color:mediumspringgreen; font-weight: bold;">ongoing...</div>
{% endif %}
</td>
</tr>
<tr>
<th><p>&nbsp</p></th>
</tr>
<tr>
<th style="color:dimgray">Goal comment</th>
<td width="18"></td>
<td></td>
</tr>
</tbody>
</table>
<div class="row">
<textarea class="form-control" readonly title="Comment" style="background-color:aliceblue !important;">{{goal.corp_goal_comment}}</textarea>
</div>
</div>
</div>
</div>
<!--Second tab-->
<div id="det2{{ goal.id }}" class="tab-pane fade" style="margin-top:20px;">
<p>Factor for Goal Achievement:</p>
<table class="table">
<tbody>
<tr>
<th>Factor</th>
<td>0</td>
<th>Description</th>
<td>{{ goal.corp_factor_0 }}</td>
</tr>
<tr>
<th>Factor</th>
<td>1</td>
<th>Description</th>
<td>{{ goal.corp_factor_1 }}</td>
</tr>
<tr>
<th>Factor</th>
<td>2</td>
<th>Description</th>
<td>{{ goal.corp_factor_2 }}</td>
</tr>
<tr>
<th>Factor</th>
<td>3</td>
<th>Description</th>
<td>{{ goal.corp_factor_3 }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<br />
<br />
<br />
{% endfor %}
{% endblock %}
And it works perfectly. But when in last block summary I want to use corporate_goals one more time - I have nothing on my page, looks like corporate_goals is not exist.
my summary.html
{% load static %}
{% block content %}
<div class="row">
<p>123</p>
</div>
<div class="row">
{% for goal, compl_weight in corporate_goals %}
{{ goal.corp_goal_title }}
{% endfor %}
</div>
<div class="row">
<p>123</p>
</div>
{% endblock %}
Even If I copy all my code from corporate_goal.html into summary - I will have nothing. Why ?
I think that the problem is that your html structure has no sense. You have three {% block content %}. Please, delete the content blocks of your include files (corporate_goal.html and summary.html) and check if this is the problem. I think that one of your content block is overriding the other one.
Just to clarify, when you use the "include tag" is like you were pasting the code from other file. So imagine the result. You have a block content that contains two other block contents inside it.
My problem was in zip objects. When we are iterating through a zip object it is exhausted and you cannot iterate through it again. So, solution is corporate_goals = list(zip(corp_goals, compl_weight)). Anyway, thank you, #LaCharcaSoftware, for the advice, I've changed my structure to avoid duplication with block content.

Passing context to django admin index page

I'm trying to create a table on django admin's index page, listing all users registered in a specific timeframe. I've managed to already edit the index page to include my table but I now want to populate the table. I tried declaring the extra_context variable but it still doesn't pass it to the template. I've been on this issue for days and still can't figure out what I'm doing wrong. This is my admin.py file
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from .forms import SignUpForm, EditUserForm
from .models import CustomUser
from django.urls import path
from datetime import datetime, timedelta
from django.utils import timezone
class CustomUserAdmin(UserAdmin):
list_filter = ['created_at',]
list_display = ['username', 'email', 'created_at', 'is_active']
# index_template = 'admin/my_index.html'
def time_threshold(num):
num = int(num)
thresh = datetime.now(tz=timezone.utc) - timedelta(hours=num)
return thresh
print(time_threshold(30))
def get_urls(self):
urls = super().get_urls()
custom_urls = [
path("user_metrics/", self.user_metrics),
]
return custom_urls + urls
def user_metrics(self, request, extra_context=None):
extra_context = extra_context or {}
user_24 = CustomUser.objects.filter(created_at__gt=time_threshold(730))
extra_context['users_in_past_24_hours'] = CustomUser.objects.filter(created_at__gt=time_threshold(24))
extra_context['users_in_past_week'] = CustomUser.objects.filter(created_at__gt=time_threshold(168))
extra_context['users_in_past_month'] = CustomUser.objects.filter(created_at__gt=time_threshold(730))
print(user_24)
return super(CustomUserAdmin, self).user_metrics(request, extra_context=extra_context)
admin.site.register(CustomUser, CustomUserAdmin)
admin.site.unregister(Group)
admin.site.site_header = "Savests Custom Admin"
And this is my index.html file I have inside template/admin folder
{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}">{% endblock %}
{% block coltype %}colMS{% endblock %}
{% block bodyclass %}{{ block.super }} dashboard{% endblock %}
{% block breadcrumbs %}{% endblock %}
{% block nav-sidebar %}{% endblock %}
{% block content %}
<div id="content-main">
{% include "admin/app_list.html" with app_list=app_list show_changelinks=True %}
</div>
<div>
<h5>Users in the last 24 hours</h5>
<table class="table table-hover table-bordered">
<caption>User Information</caption>
<thead class="thead-dark">
<th>User ID</th>
<th>Username</th>
<th>Email Address</th>
<th>Active Status</th>
<th>Staff Status</th>
</thead>
{% for a in users_in_past_24_hours %}
<tr>
<td>{{ a.id }}</td>
<td>{{ a.username }}</td>
<td>{{ a.email }}</td>
<td>
{% if a.is_active %}
<form action="{% url 'toggle_user_status_false' user_id=a.id %}" method="post">
{% csrf_token %}
<button class="btn btn-danger" type="submit">
Deactivate
</button>
</form>
{% else %}
<form action="{% url 'toggle_user_status_true' user_id=a.id %}" method="post">
{% csrf_token %}
<button class="btn btn-primary" type="submit">
Activate
</button>
</form>
{% endif %}
</td>
<td>
{% if a.is_staff %}
Staff
{% else %}
Not Staff
{% endif %}
</td>
</tr>
{% endfor %}
</table>
<br>
<hr>
<h5>Users in the past week</h5>
<table class="table table-hover table-bordered">
<caption>User Information</caption>
<thead class="thead-dark">
<th>User ID</th>
<th>Username</th>
<th>Email Address</th>
<th>Active Status</th>
<th>Staff Status</th>
</thead>
{% for a in users_in_past_week %}
<tr>
<td>{{ a.id }}</td>
<td>{{ a.username }}</td>
<td>{{ a.email }}</td>
<td>
{% if a.is_active %}
<form action="{% url 'toggle_user_status_false' user_id=a.id %}" method="post">
{% csrf_token %}
<button class="btn btn-danger" type="submit">
Deactivate
</button>
</form>
{% else %}
<form action="{% url 'toggle_user_status_true' user_id=a.id %}" method="post">
{% csrf_token %}
<button class="btn btn-primary" type="submit">
Activate
</button>
</form>
{% endif %}
</td>
<td>
{% if a.is_staff %}
Staff
{% else %}
Not Staff
{% endif %}
</td>
</tr>
{% endfor %}
</table>
<br>
<hr>
<h5>Users in the past month</h5>
<table class="table table-hover table-bordered">
<caption>User Information</caption>
<thead class="thead-dark">
<th>User ID</th>
<th>Username</th>
<th>Email Address</th>
<th>Active Status</th>
<th>Staff Status</th>
</thead>
{% for a in users_in_past_month %}
<tr>
<td>{{ a.id }}</td>
<td>{{ a.username }}</td>
<td>{{ a.email }}</td>
<td>
{% if a.is_active %}
<form action="{% url 'toggle_user_status_false' user_id=a.id %}" method="post">
{% csrf_token %}
<button class="btn btn-danger" type="submit">
Deactivate
</button>
</form>
{% else %}
<form action="{% url 'toggle_user_status_true' user_id=a.id %}" method="post">
{% csrf_token %}
<button class="btn btn-primary" type="submit">
Activate
</button>
</form>
{% endif %}
</td>
<td>
{% if a.is_staff %}
Staff
{% else %}
Not Staff
{% endif %}
</td>
</tr>
{% endfor %}
</table>
<br>
<hr>
</div>
{% endblock %}
{% block sidebar %}
<div id="content-related">
<div class="module" id="recent-actions-module">
<h2>{% translate 'Recent actions' %}</h2>
<h3>{% translate 'My actions' %}</h3>
{% load log %}
{% get_admin_log 10 as admin_log for_user user %}
{% if not admin_log %}
<p>{% translate 'None available' %}</p>
{% else %}
<ul class="actionlist">
{% for entry in admin_log %}
<li class="{% if entry.is_addition %}addlink{% endif %}{% if entry.is_change %}changelink{% endif %}{% if entry.is_deletion %}deletelink{% endif %}">
{% if entry.is_deletion or not entry.get_admin_url %}
{{ entry.object_repr }}
{% else %}
{{ entry.object_repr }}
{% endif %}
<br>
{% if entry.content_type %}
<span class="mini quiet">{% filter capfirst %}{{ entry.content_type.name }}{% endfilter %}</span>
{% else %}
<span class="mini quiet">{% translate 'Unknown content' %}</span>
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
</div>
{% endblock %}
1st way is to declare subclass django.contrib.admin.site.AdminSite() and override the .index() method in admin.py
class MyAdminSite(django.contrib.admin.site.AdminSite):
def index(self, request, extra_context=None):
if extra_context is None:
extra_context = {}
user_24 = CustomUser.objects.filter(created_at__gt=time_threshold(730))
extra_context['users_in_past_24_hours'] = CustomUser.objects.filter(created_at__gt=time_threshold(24))
extra_context['users_in_past_week'] = CustomUser.objects.filter(created_at__gt=time_threshold(168))
extra_context['users_in_past_month'] = CustomUser.objects.filter(created_at__gt=time_threshold(730))
extra_context["app_list"] = get_app_list_in_custom_order()
return super(MyAdminSite, self).index(request, extra_context)
then you should register your site admin (also in admin.py)
my_admin_site = MyAdminSite(name='myadmin')
when you create your own AdminSite you need to register all models using it, so instead of
admin.site.register(YourModel) you should use my_admin_site.register(YourModel) for all models you use. you also need to add path to your adminsite in urls.py
from pathtoyouradmin.admin import my_admin_site
urlpatterns = [
...
path('admin/', my_admin_site.urls),
...
]
you can solve your problem other way. you can create contextprocessor where you check path of current page and if it admin index then provide needed extra_context
def context_users_info(request):
extra_context = {}
if request.path == 'index admin page'# you need to put path to your index admin page
user_24 = CustomUser.objects.filter(created_at__gt=time_threshold(730))
extra_context['users_in_past_24_hours'] = CustomUser.objects.filter(created_at__gt=time_threshold(24))
extra_context['users_in_past_week'] = CustomUser.objects.filter(created_at__gt=time_threshold(168))
extra_context['users_in_past_month'] = CustomUser.objects.filter(created_at__gt=time_threshold(730))
extra_context["app_list"] = get_app_list_in_custom_order()
return extra_context
and don't forget to register your context processor in settings.py

Django how to forward django-filter URL named parameters

I'm new to django so i could be asking a dumb question, but how am i supposed to forward URL A's named parameter to URL B?
For example:
URL A = https://stackoverflow.com/questions?parameter=1
URL B = https://stackoverflow.com/ask
What i actually want is:
URL B = https://stackoverflow.com/ask?parameter=1
I need to do this because i need to pass those parameters to the view that is being called at the second url, could someone help me?
EDIT1
The views that are at play are this two:
class HostServiceListView(BaseFilterView, ListView):
template_name = 'services/service_list.html'
model = HostService
paginate_by = 15
context_object_name = 'services'
filterset_class = HostServiceFilterSet
def exportHostServices(request):
hsqs = HostService.objects.filter(hostname__icontains=request.GET.get("hostname_input", ''),\
ip__icontains=request.GET.get("ip_input", ''),\
port__icontains=request.GET.get("port_input", ''),\
servicename__icontains=request.GET.get("servicename_input", ''))
df = read_frame(hsqs)
# my "Excel" file, which is an in-memory output file (buffer)
# for the new workbook
excel_file = IO()
# pylint shows a false positive error here,
# so the alert is suppressed with the comment after the code
xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter') # pylint: disable=abstract-class-instantiated
df.to_excel(xlwriter, 'Host Services')
xlwriter.save()
xlwriter.close()
# rewind the buffer
excel_file.seek(0)
# set the mime type so that the browser knows what to do with the file
response = HttpResponse(excel_file.read(),\
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
# set the file name in the Content-Disposition header
response['Content-Disposition'] = 'attachment; filename=Anagrafica-Servizi.xlsx'
return response
The urls.py is configured this way:
urlpatterns = [
path('services/', HostServiceListView.as_view(), name='services'),
path('services/exportHostServices/', exportHostServices, name='exportHostServices'),
path('', IndexFilterView, name="index")
]
Finally, the button i've got in html that needs to call exportHostServices with the query-string so i can get the parameters:
services/service_list.html
{% extends 'services/base.html' %}
{% load paginatedfilter %}
{% block title %}Host Services{% endblock title %}
{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Service Registry</h1>
<div class="btn-toolbar mb-2 mb-md-0">
<div class="btn-group mr-2">
<form action="{% url 'exportHostServices' %}?{{ request.GET.urlencode }}">
<input type="submit" class="btn btn-sm btn-outline-secondary" value="Export">
</form>
</div>
</div>
</div>
<div class="table-responsive table-sm">
<form method="GET">
<input type="submit" class="btn-hidden"/>
<table class="table table-hover table-light table-striped">
<thead class="thead-light">
<tr>
<th>{{ filter.form.hostname_input }}</th>
<th>{{ filter.form.ip_input }}</th>
<th>{{ filter.form.port_input }}</th>
<th>{{ filter.form.servicename_input }}</th>
</tr>
</thead>
<tbody>
{% for service in services %}
<tr>
<td>{{ service.hostname }}</td>
<td>{{ service.ip }}</td>
<td>{{ service.port }}</td>
<td>{{ service.servicename }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if is_paginated %}
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?{% param_replace page=page_obj.previous_page_number %}" aria-label="previous">
<span aria-hidden="true">«</span>
</a>
</li>
{% endif %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="page-item active" aria-current="page">
<span class="page-link">
{{ i }}
<span class="sr-only">(current)</span>
</span>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="?{% param_replace page=i %}">{{ i }}</a>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?{% param_replace page=page_obj.next_page_number %}" aria-label="next">
<span aria-hidden="true">»</span>
</a>
</li>
{% endif %}
</ul>
{% endif %}
</form>
</div>
{% endblock content %}
Figured out atlast what was wrong with the code. The problem was that the form where i passed the querystring was defaulted at GET:
<form action="{% url 'exportHostServices' %}?{{ request.GET.urlencode }}">
The fix was to simply convert it to a POST form so the querystring could be passed to the view:
<form action="{% url 'exportHostServices' %}?{{ request.GET.urlencode }}" method="post">

Second loop is not executing in django template

HI I have very strange problem .
Here is my template
<table class="table table-striped table-condensed tablesorter" id="myTable">
<thead>
<tr>
<th>Store</th>
<th>Image</th>
<th>Price(USD)</th>
<th>Manufacturer</th>
<th>Model</th>
<th>Shipping</th>
<th>Replacement</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{% for x in result_amazon|slice:"1" %}
{% if forloop.first %} <tr>
<td>
<a href="" target="_blank">
<img height="85" width="110" src={% static "images/Amazon-Logo.jpg" %} alt="">
</a>
</td>
<td><img src={{x.medium_image_url}} alt=""></td>
<td><strong><span class="WebRupee"></span>
{% for y in x.list_price %}
{% if y.price != 'None'%}
{{y}}
{% endif %}
{% endfor %}</strong>
</td>
<td>{{x.manufacturer}}</td>
<td>{{x.model}}</td>
<td>Rs. 99</td>
<td>Out of Stock</td>
<td>
<a href="{{x.detail_page_url}}" class="btn btn-mini btn-primary trackinfo" rel="7###17205" title="Visit Store" target="_blank">
Visit Store
</a>
</td>
</tr>
{% endif %}
{% endfor %}
{% for x in result_bestbuy.products %}
{% if forloop.first %}
<tr>
<td>
<a href="">
<img height="85" width="110" src={% static "images/bestbuy.gif" %} alt="">
</a>
</td>
<td><img style="height: 168px;" src={{x.image}} alt=""></td>
<td><strong><span class="WebRupee"></span>{{x.regularPrice}}</strong></td>
<td>{{x.manufacturer}}</td>
<td>{{x.modelNumber}}</td>
<td>{% if x.freeShipping %}Free Shipping {% else %}{{x.shippingCost }}{% endif %}</td>
<td>14 Days</td>
<td>
<a href="{{x.url}}" class="btn btn-mini btn-primary trackinfo" rel="27###17205" title="Visit Store" target="_blank">
Visit Store
</a>
</td>
</tr>
{% endif %}
{% endfor %}
{% for x in result_amazon %}
{% if not forloop.first %}
<tr>
<td>
<img height="85" width="110" src={% static "images/Amazon-Logo.jpg" %} alt="">
</a>
</td>
<td><img src={{x.medium_image_url}} alt=""></td>
<td><strong><span class="WebRupee"></span>
{% for y in x.list_price %}
{% if y.price != 'None'%}
{{y}}
{% endif %}
{% endfor %}
</strong>
</td>
<td>{{x.manufacturer}}</td>
<td>{{x.model}}</td>
<td>Rs. 99</td>
<td>Out of Stock</td>
<td>
<a href="{{x.detail_page_url}}" class="btn btn-mini btn-primary trackinfo" rel="7###17205" title="Visit Store" target="_blank">
Visit Store
</a>
</td>
</tr>
{% endif %}
{% endfor %}
{% for x in result_bestbuy.products %}
{% if not forloop.first %}
<tr>
<td>
</td>
<td><img style="height: 168px;" src={{x.image}} alt=""></td>
<td><strong><span class="WebRupee"></span>{{x.regularPrice}}</strong></td>
<td>{{x.manufacturer}}</td>
<td>{{x.modelNumber}}</td>
<td>{% if x.freeShipping %}Free Shipping {% else %}{{x.shippingCost }}{% endif %}</td>
<td>14 Days</td>
<td>
<a href="{{x.url}}" class="btn btn-mini btn-primary trackinfo" rel="27###17205" title="Visit Store" target="_blank">
Visit Store
</a>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
I am trying to limit the first loop to execute only once initially then rest all has to be executed hence I have applied the forloop.first condition .
My simple question is "Why the third loop(result_amazon) is not printing any data" (There are lot many data present in the result_amazon).
Please help me out what might I am doing wrong here .
Check the console of your browser and look for any errors in your html code.

Categories

Resources