Django NoReverseMatch while return render() - python

I always receive a NoReverseMatch error, and I don't know why.
This is the error message:
NoReverseMatch at /suche/any-thing/
Reverse for 'article_search' with arguments '(u'any thing',)' not found. 1 pattern(s) tried: ['suche/(?P[-\w]+)/$']
So as you can see, I'm entering a url with "-" instead of whitespace, but Django is looking for url pattern with the space instead of "-".
This is my url pattern:
url(r'suche/(?P<search>[-\w]+)/$', views.article_search_view, name='article_search'),
Surprisingly Django starts to compute my article_search_view, which looks like this:
def article_search_view(request, search=None):
"""Filters all articles depending on the search and renders them"""
articles = get_active_not_rented_articles()
search = re.sub(r"[-]", ' ', search)
articles = articles.filter(title__icontains=search)
articles = aply_sort(request, articles)
orderd_by = articles[0].get('filter')
articles = articles[1]
return render(request, 'article/list.html', {'object_list':articles, 'url_origin':'article_search', 'parameter':search,
'orderd_by':orderd_by})
As I checked with "print()" statements, the error is raised when the return render(...) statement is called.
If I do a return redirect(...) instead, no error will be raised.
For completeness, my article/list.html template:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div id =articles>
<div class="info_filter">
<div class="header_info_filter">
{% if orderd_by == "not" %}
<h1>Neueste Artikel</h1>
{% endif %}
{% if orderd_by == "distance" %}
<h1>Artikel in Ihrer Nähe</h1>
{% endif %}
{% if orderd_by == "price_asc" %}
<h1>Günstigste Artikel zuerst</h1>
{% endif %}
{% if orderd_by == "price_des" %}
<h1>Teuerste Artikel zuerst</h1>
{% endif %}
</div>
<div class="selection">
{% if parameter1 %}
<form action="{% url url_origin parameter1 parameter2 %}" method="post" accept-charset="utf-8">
{% else %}
{% if parameter %}
<form action="{% url url_origin parameter %}" method="post" accept-charset="utf-8">
{% else %}
<form action="{% url url_origin %}" method="post" accept-charset="utf-8">
{% endif %}
{% endif %}
{% csrf_token %}
<div class="select_filter">
<select name="filter" id="filter" >
<option value="distance">Entfernung</option>
<option value="price_asc">Preis, aufsteigend</option>
<option value="price_des">Preis, absteigend</option>
</select>
<div class="search_filter_btn">
<button type="submit" name="button">Sortieren</button>
</div>
</div>
</form>
</div>
{% if parent_categorys %}
<div class="category-path">
Ergebnisse für:
{% for category in parent_categorys %}
> {{ category.name }}
{% endfor %}
{% if parameter2 %}
: {{ parameter2}}
{% endif %}
</div>
{% else %}
Ergebnisse für: {{ parameter}}
{% endif %}
</div>
<div id="main" class="article_list">
{% for article in object_list %}
<div class="item">
<div class="list_img">
<a href="{{ article.get_absolute_url }}">
<img src="{% if article.main_picture %}{{ article.main_picture.url }}{% else %}{% static "img/no_image.png" %}{% endif %}">
</a>
</div>
<div class= "articles_fee" >
{{ article.fee }} €
</div>
{{ article.title }}
</div>
{% endfor %}
</div>
</div>
{% endblock %}
Let me know if you need more information.

In your view, you change search and replace hyphens with spaces. This causes an error when you use the url tag in your template, because the URL pattern does not allow spaces.
{% url url_origin parameter %}
You could fix the problem by adding the original search slug to the template context:
def article_search_view(request, search=None):
"""Filters all articles depending on the search and renders them"""
search_slug = search
articles = get_active_not_rented_articles()
search = re.sub(r"[-]", ' ', search)
...
return render(request, 'article/list.html', {'object_list':articles, 'url_origin':'article_search', 'parameter':search, 'search_slug': search_slug, 'orderd_by':orderd_by})
Then change the url tag:
{% url url_origin search_slug %}

Related

How to call in the google books API in django?

The books are being displayed but when i click on the link it does not lead to the google books.co.in webpage where the book is stored, it displays that the page is not found.
my views.py
def books(request):
if request.method == "POST":
form=DashboardForm(request.POST)
text=request.POST['text']
url="https://www.googleapis.com/books/v1/volumes?q="+text
r = requests.get(url)
answer = r.json()
result_list = []
for i in range(10):
result_dict = {
'title':answer['items'][i]['volumeInfo']['title'],
'subtitle':answer['items'][i]['volumeInfo'].get('subtitle'),
'description':answer['items'][i]['volumeInfo'].get('description'),
'count':answer['items'][i]['volumeInfo'].get('pageCount'),
'categories':answer['items'][i]['volumeInfo'].get('categories'),
'rating':answer['items'][i]['volumeInfo'].get('pageRating'),
'thumbnail':answer['items'][i]['volumeInfo'].get('imageLinks').get('thumbnail'),
'preview':answer['items'][i]['volumeInfo'].get('previewLinks')
}
result_list.append(result_dict)
context={
'form' : form,
'results' :result_list
}
return render(request,'dashboard/books.html',context)
else:
form=DashboardForm()
context={'form' : form}
return render(request,'dashboard/books.html',context)
my books.html template
{% extends 'dashboard/base.html' %}
{% load static %}
{% block content %}
<section class='text-center container'>
<h2><b>SEARCH FOR BOOKS </b></h2>
<p>Enter the search query to obtain your desired book</p><b></b>
<form action="" method="post">
{% csrf_token %}
{{form}}
<input class="btn btn-danger" type="submit" value="Submit">
</form><br>
{% for result in results %}
<a href="{{result.preview}}" target="_blank">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-3">
<img class="img-fluid" src="{{result.thumbnail}}" alt="">
</div>
<div class="col-md-9">
<h3 class="p-0 m-0">{{result.title}}</h3>
<b>
<u>
<h5 class="p-0 m-0">{{result.subtitle}}</h5>
</u>
</b>
{% if result.description %}
<h6 class="p-0 m-1">{{result.description}}</h6>
{% endif %}
<b>
{% if result.categories %}
<h6 class="ml-0 mt-3">Category:
{% for category in result.categories %}
{{category}}
{% endfor %}
</h6>
{% endif %}
{% if result.count %}
<h6 class="ml-0 mt-1">Pages: {{result.count}}</h6>
{% endif %}
{% if result.rating %}
<h6 class="ml-0 mt-1">Rating:{{result.rating}}</h6>
{% endif %}
</b>
</div>
</div>
</div>
</div>
</a>
{% endfor %}
<br>
</section>
{% endblock content %}
I have installed and imported requests and want to redirect to google books page when i click on the book.
enter image description here
The issue seems to be with the value of "preview" in the "result_dict" dictionary. It looks like the "previewLinks" key in the JSON response from the Google Books API does not contain a URL that can be directly accessed.
You can try it like this:
result_dict = {
...
'preview': answer['items'][I]['volumeInfo'].get('previewLinks').get('googlePlay'),
...
}

Django html Check form type

I'm trying to build an html page in Django, where depending on the form passed the page will render different things. How can I know in the HTML the type of form passed?
I want to do something like this:
{% block content %}
<div class="content-section container" >
{% if form.type == 'ModelAForm' %}
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.driver_color }}
</form>
</div>
{% endif %}
{% if form.type == 'ModelBForm' %}
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.driver_name}}
</form>
</div>
{% endif %}
</div>
{% endblock content %}
On the {% if form.type == 'ModelAForm' %} how can I know the form type?

Reverse for 'django_markdown_preview' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

I am using django_markdown but it is showing error when I am trying to render form. The error is on 17th line {{ form }} Error. The error is in reverse of 'django_markdown_preview', but I have included
url('^markdown/', include('django_markdown.urls')),
in my urls.py. Can anyone help me to resolve the error.
{% extends 'qaforum/base.html' %}
{% load django_markdown %}
{% block content %}
{% if message %}
<strong>Enter a valid Question!</strong>
{% endif %}
<form method="post" action="{% block action_url %}{% url 'qaforum:qaforum_create_question' %}{% endblock action_url %}">
{% csrf_token %}
{% for field in form.visible_fields %}
<tr>
<th>{{ field.label_tag }}</th>
<td>
{{ field.errors }}
{{ field }}
{{ field.help_text }}
</td>
</tr>
{% endfor %}
<input class="btn pull-right btn-success" type="submit" value="Submit Question" />
</form>
</div>
{% endblock content %}
{% block extra_js %}
{% markdown_editor "#id_description" %}
{% markdown_media %}
{% endblock extra_js %}

My Django if statement do not work correctly

I have created a admin panel on the frontend and would like to show different layouts if they are on the index.html or if they are on pages after /admin e.g:
/admin/dashboard
/admin/posts
/admin/media
My if statement:
{% if request.path == "/admin" %}
It doesn't work for some reason and I can't figure out why. This is an example of the whole if:
<div class="row">
{% if request.path == "/admin" %}
<div class="col-md-full">
{% else %}
<div class="col-md-7 left">
{% block main %}{% endblock %}
</div>
{% endif %}
{% if request.path == "/admin" %}
{% trans "Empty" %}
{% else %}
<div class="col-md-3 right">
<div class="panel panel-default">
<div class="panel-body">
{% block right_panel %}
{% endblock %}
</div>
</div>
</div>
{% endif %}
</div>
what about?
{% if '/admin/' in request.path %}

Checking if authenticated in Django template inheritance

I have the following code in a template and am having difficulty showing when a user is logged in. I will be able to login, but when I revisit the page, it shows that I'm still not authenticated.
{% extends "base.html" %}
{% load catalog_tags %}
{% block site_wrapper %}
<div id = "main">
Skip to main content
<div id = "banner">
<div class="bannerIEPadder">
<div class="cart_box">
{% cart_box request %}
</div>
</div>
</div>
<div style="float:right;">[search box goes here]</div>
<div id="navigation">
<div class="navIEPadder">
<!--navigation tabs at the top of each page -->
{% comment %}{% include "tags/navigation.html" %} {% endcomment %}
{% category_list request.path %}
</div>
</div>
<div id="middle">
<div id="sidebar">
<!--<div class="sidebarIEPadder">[search box goes here]</br>
{% comment %}{% category_list request.path %}{% endcomment %}
</div>-->
</div>
<div id="content">
<!-- <a name = "content"></a>-->
<div class="contentIEPadder">
{% block content %}{% endblock %}
</div>
</div>
</div>
<div id="footer">
<div class="footerIEPadder">
{% footer_links %}
</div>
</div>
</div>
{% endblock %}
And here's the file it references. Since this will be an extension of all templates, is there something I need to consider?
###category_list.html
<!--<h3>Categories</h3>-->
<!--<ul id="categories">-->
<ul>
{% with active_categories as cats %}
{% for c in cats %}
<li>
{% comment %}
{% ifequal c.get_absolute_url request_path %}
{{c.name}}
{% else %}
{% endcomment %}
<div>{{c.name}}</div>
{% comment %}{% endifequal %}{% endcomment %}
</li>
{% endfor %}
<div class="fr">
<ul>
<li>
{% if user.is_authenticated %}
Logout
{% else %}
Login
{% endif %}
</li>
</div>
{% endwith %}
</ul>
<div class="cb"></div>
Am I missing something here?
You need to pass a RequestContext to the template. The easiest way to do this is to import django.shortcuts and use the render method in your view:
return render(request, "my_template.html")
Is django.contrib.auth.context_processors.auth in your TEMPLATE_CONTEXT_PROCESSORS setting.py?
Do you use requestContext rendering template?
Check that sessions are enabled: MIDDLEWARE_CLASSES should contains 'django.contrib.sessions.middleware.SessionMiddleware'

Categories

Resources