I've been trying to write a custom template tag to shorten links with bitly, I've attached the code and error I've been getting below. I've tried to look into the documentation provided by Django but cannot see what it is that I am doing wrong.
I've put my templatetag in the following layout:
scribbler/
models.py
templatetags/
__init__.py
shortenlink.py
views.py
the custom tag file that I've written:
shortenlink.py
from django import template
from django.conf import settings
from urllib import urlencode
from urllib2 import urlopen
register = template.Library()
#register.simple_tag
def bitlyshort(the_url):
endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}&format=txt'
req = urlencode(endpoint.format(settings.ACCESS_KEY, the_url))
return urlopen(req).read()
part of the template that uses the template tag:
template
{% load shortenlink %}
<p>{{ bitlyshort "http://www.google.com" }}</p>
error
TemplateSyntaxError at /user/sankaetp/
Could not parse the remainder: ' "http://www.google.com"' from 'bitlyshort "http://www.google.com"'
Request Method: GET
Request URL: http://localhost:8000/user/sankaetp/
Django Version: 1.4.1
Exception Type: TemplateSyntaxError
Exception Value:
Could not parse the remainder: ' "http://www.google.com"' from 'bitlyshort "http://www.google.com"'
Exception Location: /Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/django/template/base.py in __init__, line 563
Python Executable: /Users/sankaetp/virtualenvs/myproject/bin/python
Python Version: 2.7.3
Python Path:
['/Users/sankaetp/virtualenvs/myproject/bin/django_worksquid',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/pip-1.1-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/djangoembed-0.1.1-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/httplib2-0.7.4-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/BeautifulSoup-3.2.1-py2.7.egg',
'/Users/sankaetp/virtualenvs/myproject/lib/python27.zip',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/plat-darwin',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/plat-mac',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/lib-tk',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/lib-old',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/lib-dynload',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/plat-darwin',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/lib-tk',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/plat-mac',
'/Users/sankaetp/.pythonbrew/pythons/Python-2.7.3/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages',
'/Users/sankaetp/virtualenvs/myproject/lib/python2.7/site-packages/PIL']
Server time: Sun, 26 Aug 2012 18:54:26 -0500
The error is on this line:
<p>{{ bitlyshort "http://www.google.com" }}</p>
Template tags use {% ... %} (template filters use {{ ... }}). Try:
<p>{% bitlyshort "http://www.google.com" %}</p>
There is an alternative way to cause this error:
Instead of:
{{ data|filter }}
If you use:
{{ data | filter }} <!-- Note Spaces -->
The spaces on either side of the | character will cause an exception during page render.
Related
i tried to add a url in django template which is supposedly to log out a user
<div>logout</div>
but it threw a NoReverseMatch
the template:
<header class="grid-header header">
<div class='logo-text'>Nitro fleet</div>
<div class="profile-detail">
{% if user.is_authenticated %}
<img class="profile-img" src="{{user.picture.url}}" />
<div>
<div>{{user.username}}</div>
<div>logout</div>
</div>
{%endif%}
</div>
</header>
the url of the app (accounts) that has the logout view:
from django.urls import path
from . import views
appname = 'accounts'
urlpatterns = [
path('register', views.register_view , name='user_register'),
path('login', views.user_login , name='user_login'),
path('logout', views.user_logout , name='user_logout'),
]
the view function:
def user_logout(request):
logout(request)
return HttpResponseRedirect(request.path_info)
the complete error log:
NoReverseMatch at /maintenance/
Reverse for 'accounts.views.user_logout' not found. 'accounts.views.user_logout' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/maintenance/
Django Version: 3.2.9
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'accounts.views.user_logout' not found. 'accounts.views.user_logout' is not a valid view function or pattern name.
Exception Location: C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix
Python Executable: C:\Users\PC\AppData\Local\Programs\Python\Python310\python.exe
Python Version: 3.10.0
Python Path:
['C:\\Users\\PC\\Desktop\\nitrofleet',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\DLLs',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\lib',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310',
'C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages']
Server time: Mon, 31 Jan 2022 20:43:51 +0000
Just use the name of the view:
{% url 'accounts:user_logout' %}
When using the django url tag with a dynamic parameter in a Django template, the following snippet:
<ul>
{% for m in markets %}
<li>{{ m.mic }}</li>
{% endfor %}
</ul>
is always generating a NoReverseMatch exception:
Error during template rendering
In template D:\X\django\project0\core\templates\markets\index.html, error at line 29
Reverse for 'market_detail' with keyword arguments '{'market_mic': ''}' not found. 1 pattern(s) tried: ['core/market/(?P<market_mic>[^/]+)/$']
It is configured like this in core/urls.py:
from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
# ex: /core/market/
path('market/', views.market_index, name='market_index'),
# ex: /core/market/XPAR/
path('market/<str:market_mic>/', views.market_detail, name='market_detail'),
# ex: /core/market/XPAR/all
path('market/<str:market_mic>/all', views.market_all_udls, name='market_all_udls'),
When trying to get the reverse with the shell (python manage.py shell), it works:
In [5]: reverse('core:market_detail', kwargs={'market_mic': 'XPAR'})
Out[5]: '/core/market/XPAR/'
It is likely Django is unable to resolve the market variable in the url tag while elsewhere it is rendering it as expected.
I'm working on a basic Django app (just learning, this is my third small project), and I'm trying to add links to allow a list of every post a user has made. I've got the URLS being created OK (domain/posts/username), and I want this to link to a view (that I've already created, and which works when the parameters I want to pass are hard-coded to a single value), passing the positional arguments to the view. However, I'm running aground on the RegEx / Urls part of things. I think this is the relevant info:
urls.py:
urlpatterns = [
url(r'^create/', views.create, name='create'),
url(r'^(?P<pk>[0-9]+)/upvote', views.upvote, name='upvote'),
url(r'^(?P<pk>[0-9]+)/downvote' , views.downvote, name='downvote'),
url(r'^userposts/(?P<user>[.]+)', views.userposts, name='userposts')
views.py
def userposts(request,user):
posts = models.Post.objects.filter(url__contains=user)
return render(request, 'posts/userposts.html', {'posts': posts})
home.html
a href="{{ post.url}}">{{ post.title }}</a><br/>{{ post.pub_date_pretty }} by
{{ post.author.username }}</td>
With the (?P[.]+) part of the last url line removed, the page will render OK, but the links don't work (as there's no user parameter being passed). With the regex present (not only this one, but the many others I've tried), I get a NoReverseMatch error:
NoReverseMatch at /
Reverse for 'userposts' with no arguments not found. 1 pattern(s) tried: ['posts/userposts/(?P<user>[.]+)']
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.11
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'userposts' with no arguments not found. 1 pattern(s)
tried: ['posts/userposts/(?P<user>[.]+)']
Exception Location: /usr/local/lib/python3.5/dist-
packages/django/urls/resolvers.py in _reverse_with_prefix, line 497
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/home/darren/redditclone/redditclone',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/home/darren/.local/lib/python3.5/site-packages',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Thu, 18 May 2017 18:21:11 +0000
Your userposts is defined like
url(r'^userposts/(?P<user>[.]+)', views.userposts, name='userposts')
which means it requires a user argument to resolve.
To pass such an argument, you'd do
{% url 'posts:userposts' user_goes_here %}
Try this instead
{{ post.author.username }}
I have split up views.py into two files, organized thus:
views/
__init__.py
public.py
private.py
In one view (in public) I render a template which has the following:
<a href='{% url app.views.private.login_view %}'>Login</a>
I get the following error when loading the url:
TemplateSyntaxError at /
Caught ViewDoesNotExist while rendering:
Could not import app.views.private.app.views. Error was: No module
named app.views
What am I doing wrong?
Try naming your url and then using that name inside the {% url ... %} tag, like so:
#urls.py
url(r'^xyz/abc/$','app.views.private.login_view', name='login_view'),
#login_view.html (template-code)
<a href='{% url login_view %}'>Login</a>
I would recommend naming your url patterns, then using the name in the {% url %} tag.
Are you using {% load url from future %} ? If so you will need to put quotes around your url so that it is {% url 'app.views.private.login_view' %}
The release notes for Django 1.3 explains it.
https://docs.djangoproject.com/en/dev/releases/1.3/#changes-to-url-and-ssi
I make google authorization (Oauth 2.0) with django-social-auth and getting error
Django Version: 1.3
Exception Type: TemplateSyntaxError
Exception Value:
Caught NoReverseMatch while rendering: Reverse for 'begin' with arguments '(u'google-oauth2',)' and keyword arguments '{}' not found.
Exception Location: /usr/local/lib/python2.6/site-packages/django/template/defaulttags.py in render, line 450
Python Executable: /usr/local/bin/python
Python Version: 2.6.6
Template
<a rel="nofollow" href="{% url begin "google-oauth2" %}" ><img src="{{ MEDIA_URL }}social/google.png" id="google"></a>
url.py
urlpatterns = patterns('',
url(r'', include('social_auth.urls')),
)
social_auth.urls
urlpatterns = patterns('',
url(r'^login/(?P<backend>[^/]+)/$', auth, name='begin'),
url(r'^complete/(?P<backend>[^/]+)/$', complete, name='complete'),
url(r'^associate/(?P<backend>[^/]+)/$', associate, name='associate_begin'),
url(r'^associate/complete/(?P<backend>[^/]+)/$', associate_complete,
name='associate_complete'),
url(r'^disconnect/(?P<backend>[^/]+)/$', disconnect, name='disconnect'),
)
What am I doing wrong?
Please help to find the solution.
You are on django 1.3. Have you included the new url template tag with {% load url from future %}. If you have then your syntax for the url tag is incorrect and would need to be {% url 'begin' 'google-oauth2' %}. If you haven't then your syntax is correct.
Have you ensured that your social_auth.urls is being included correctly? To do this (with debug enabled) manually go to http://yourdevserver/login/google-oauth2/ and ensure you don't see a 404 page. If you do you will be able to see what url's where attempted and that should give you direction on how to fix it.