Could not parse the remainder: ':' from '1:' - django

TemplateSyntaxError at /challeges/1
Could not parse the remainder: ':' from '1:'
This is my challege.html
{% if month == 1: %}
<h1>This is {{ text }}</h1>
{% else: %}
<p>This is {{ text }}</p>
{% endif %}
This is my views.py
def monthly_challege(request, month):
return render(request, "challeges/challege.html", {
"text": "Your Url Is Empty",
month: month
})
This is my urls.py
urlpatterns = [
path("<month>", views.monthly_challege),
]

You have a typo in your if ... else ... statement.
It should be
{% if month == 1 %}
<h1>This is {{ text }}</h1>
{% else %}
<p>This is {{ text }}</p>
{% endif %}
as per doc if else doc

I found it, here is mistake
you have to remove semicolon
before
{% if month == 1: %}
<h1>This is {{ text }}</h1>
{% else: %}
<p>This is {{ text }}</p>
{% endif %}
after
{% if month == 1 %}
<h1>This is {{ text }}</h1>
{% else %}
<p>This is {{ text }}</p>
{% endif %}

Related

Error during template rendering / Could not parse some characters

Im trying to get a bio info for each profile, when running server and going to accounts/profile y find this error:
Could not parse some characters: |% with website=profile.website| | default:"" %
{% extends 'base.html' %}
{% block title %}Profile{% endblock %}
{% block content %}
<h1>
{{ user.get_null_name }} (#{{ user.username }})
</h1>
{% with profile=user.profile %}
{% if profile %}
<h2>
{{ profile.persona }}
</h2>
<div>
{{ profile.bio|default:"" }}
</div>
<div>
{{ % with website=profile.website | default:"" % }}
{{website}}
{% endwith %}
</div>
<br/>
<div>
Interest:
{% for Interest in profile.interest.all %}
<span>
{{ interest.name }}{% if not forloop.last %}, {% endif %}
</span>
{% endfor %}
</div>
{% endif %}
{% endwith %}
{% endblock %}
A template tag does not use double curly brackets ({{ … }}), but single ones, with the % immediately followed by that (so {% … %}). The {% with … %} block in your template uses double curly brackets:
{% with website=profile.website|default:'' %}
…
{% endwith %}

How to display text if the field is empty?

How to display a text if the field is empty ?
I tried the following code but it does not work :
{% if content.field_description is not empty %}
{{ content.field_description }}
{% else %}
test
{% endif %}
If you have Twig Tweak installed, you can do the following:
{% if content['field_description'] | field_value != '' %}
{{ content['field_description'].value | striptags }}
{% else %}
<p class="des-empty">test</p>
{% endif %}
When field is empty it is not coming with content variable
so you can simply check by isset
{% if content.field_description %}
{{ content.field_description }}
{% else %}
<p class="des-empty">test</p>
{% endif %}
The below worked for me:
{% if content['field_description'] IS NOT EMPTY %}
{{ content['field_description'].value | striptags }}
{% else %}
<p class="des-empty">test</p>
{% endif %}
Please note that it may vary based on the content type and fields you are dealing with.

Fix bootstrap table in weasyprint generated PDF

I'm trying to create a PDF table with Weasyprint in my Django website. The same table is shown in a html page and with Weasyprint. When I use bootstrap colors in the html version it shows correctly, but the colors are lost on the Weasyprint version. That is the only feature missing on the Weasyprint version, which works otherwise.
views.py
#login_required
def scale_answer_pdf(request, scale_id):
scale = get_object_or_404(UserScale, pk=scale_id)
if scale.user == request.user or request.user.is_superuser:
if scale.scale_meta.title == "Now":
choices = NowLegend
class ScaleForm(forms.ModelForm):
class Meta:
model = NowModel
fields = labellist(NowLabels)
labels = NowLabels
if scale.scale_meta.title == "Child":
choices = NowLegend
class ScaleForm(forms.ModelForm):
class Meta:
model = ChildModel
fields = labellist(ChildLabels)
labels = ChildLabels
form = ScaleForm(instance=scale)
**html = render_to_string('diagnosis/scale_answer_pdf.html',
{'form': form, 'scale':scale, 'choices':choices})
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename="{} - {} -
{}.pdf"'.format(scale.scale_meta.title, scale.user.username,
scale.created.strftime('%Y-%m-%d'))
weasyprint.HTML(string=html,
base_url=request.build_absolute_uri()).write_pdf(response,
presentational_hints=True, stylesheets=
[weasyprint.CSS(settings.STATIC_ROOT + '/css/sb-admin-2.min.css'),
weasyprint.CSS(settings.STATIC_ROOT +'/css/all.min.css')])
return response**
else:
raise Http404
html for the PDF - the boostrap CSS works, and the table is also showing. But the colors from the table don't. I highlight the table parts that don't show colors
{% extends "base_pdf.html" %}
{% load i18n %}
{% load staticfiles %}
{% load get_item %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-6 mx-auto" >
<p class="text-center"><img height="120" width="120" src="{{scale.scale_meta.icon.url}}" alt="Test icon" class="img-fluid"></p>
</br>
<h1 class="text-center">{{scale.meta.title}}</h1>
{% with scale.created as created %}
{% with scale.user.username as username %}
<h4 class="text-center">{% blocktrans %}Created the {{created}} by {{username}}{% endblocktrans %}</h4>
</br>
<table class="table table-striped">
<tbody>
**<tr class="table-info">**
<td>{% trans "Question" %}<td>
<td>{% trans "Answer type" %}<td>
<td>{% trans "Answer" %}<td>
</tr>
{% for field in form %}
{% with name=field.name %}
{% if choices|get_item:name == "0 to 6" %}
{% if field.value > "4" %}
**<tr class="table-danger">**
{% endif %}
{% if field.value > "2" and field.value < "5" %}
**<tr class="table-warning">**
{% endif %}
{% if field.value <= "2" %}
**<tr class="table-success">**
{% endif %}
{% elif choices|get_item:name == "0 to 10" %}
{% if field.value <= "4" %}
**<tr class="table-danger">**
{% endif %}
{% if field.value > "4" and field.value < "7" %}
**<tr class="table-warning">**
{% endif %}
{% if field.value >= "7" %}
**<tr class="table-success">**
{% endif %}
{% endif %}
<td>{{field.label}}<td>
<td>{{choices|get_item:name}}<td>
<td >{{field.value}}<td>
</tr>
{% endwith %}
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<br/>
<br/>
{% endwith %}
{% endwith %}
{% endblock %}
BootStrap and files.CSS don't work right in weasyprint,
Is better you use CSS <style> in Html File.
Like that:
<style> /* use CSS into style */
#page {
size: A4; /* Change from the default size of A4 */
margin: 3.5mm; /* Set margin on each page */
}
</style>
Bye.

is_paginated not working properly for class based views in Django

book_list.html
{% extends "base.html" %}
{% block content %}
<h3> Available books </h3>
{% if book_list %}
<ul>
{% for book in book_list %}
<li> {{book.title }} <small> by {{book.author }}</small></li>
<p>{{ book.summary }}
{% endfor %}
<ul>
{% endif %}
{% if is_paginated %}
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
</div>
{% else %}
<h4> pagination not working</h4>
{% endif %}
{% endblock %}
class in views.py :
class BookListView(generic.ListView):
model = Book
paginate_by = 2
queryset =Book.objects.all()
urls.py :
urlpatterns =[
url('^$',views.index, name ='index'), # matching with an empty string
url('^books/$',views.BookListView.as_view(),name ='books'), #the one to which I am adding the paginator
url('^book/(?P<pk>\d+)/$',views.BookDetailView.as_view(),name='book-detail'),
]
Book model :
class Book(models.Model):
title=models.CharField(max_length=100)
author = models.ForeignKey('Author',on_delete=models.SET_NULL,null = True)
summary = models.TextField(max_length=200,help_text="Enter the description")
isbn = models.CharField('ISBN',max_length=13 ,help_text='13 Character ISBN number' )
genre = models.ManyToManyField(Genre,help_text = 'selct a genre for this book')
class Meta:
ordering =["title"]
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('book-detail',args=[str(self.id)] )
The book_list gets rendered perfectly, the problem is with the paginator, the is_paginated condition is not working and it executes the else statement, I have been trying for more than 3 hours, but couldn't find a solution, What Am I missing here ?
Django version : 1.11.2
Python : 3.5
Edit :
update 1: The problem was the paginate_by value was two, and the total items to display was also two hence it didn't initiate the is_paginated tag,It worked fine when I added one item more than paginate_by value.
use this, you had some problem with the if condition
{% extends "base.html" %}
{% block content %}
<h3> Available books </h3>
{% if object_list %}
<ul>
{% for book in object_list %}
<li> {{book.title }} <small> by {{book.author }}</small></li>
<p>{{ book.summary }}
{% endfor %}
<ul>
{% if is_paginated %}
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
</div>
{% else %}
<h4> pagination not working</h4>
{% endif %}
{% else %}
<h4> No book</h4>
{% endif %}
{% endblock %}

How can I get a variable passed into an included template in django

I am a Django newbie and am unable to achieve something trivial. Please help me with this.
I am setting a variable pgurl in my views.py
Am able to access the variable {{pgurl}} in my with_tag.html template. This template includes a pagination.html template into itself
In pagination.html I am unable to use the variable {{pgurl}} and nothing is printed
How can I get this variable passed into the included template?
views.py
def with_tag(request, tag, template_name='main/with_tag.html', current_page=1, pgurl=''):
if request.method == 'GET':
query_tag = Tag.objects.get(name=tag)
primes = TaggedItem.objects.get_by_model(Prime, query_tag)
primes = primes.order_by('-date')
request.page = current_page
tcm_pp = TCM_ITEMS_PER_PAGE
pgurl = request.path
else:
return HttpResponseRedirect(request.path)
return direct_to_template(request, template_name, { 'primes' : primes, 'prime_total' : Prime.objects.count(), 'now': datetime.now(), 'page' : current_page, 'tcm_pp' : tcm_pp, 'tag' : tag, 'pgurl' : pgurl })
with_tag.html
{% extends "base.html" %}
{% load comments %}
{% load pagination_tags %}
...
{% include "pagination.html" %}
{% paginate %}
pagination.html
{% if is_paginated %}
{% load i18n %}
<div class="pagination">
{% if page_obj.has_previous %}
‹‹ {% trans "previous" %}
{% else %}
<span class="disabled prev">‹‹ {% trans "previous" %}</span>
{% endif %}
{% for page in pages %}
{% if page %}
{% ifequal page page_obj.number %}
<span class="current page">{{ page }}</span>
{% else %}
{{ page }}
{% endifequal %}
{% else %}
...
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
{% trans "next" %} ››
{% else %}
<span class="disabled next">{% trans "next" %} ››</span>
{% endif %}
</div>
{% endif %}
It will be helpful if you post the output of the rendered page. The context should get passed, might be your template tags instead. Try to do assert and check to see if the variables were passed correctly.