Django 0.96 and url - django

I want to get the absolute url of a given action in Django 0.96 (using Google App Engine).
I have this url configuration:
from django.conf.urls.defaults import patterns
urlpatterns = patterns('framework.facebook',(r'^canvas/invite_friends$','views.inviteFriends'),
)
In my template:
window._url = '{% url views.inviteFriends %}';
I don't understand why this doesn't work.

Syntax for url is package.package.module.function args so if you replace 'views' with your module/ application name it should work.
{% url app_name.inviteFriends %}
An example:
If the full path to your function is myproject.myapp.views.inviteFriends code would be:
{% url myapp.inviteFriends %}
or
{% url myproject.myapp.inviteFriends %}

Related

Url namespace not being registered for python social auth

I have a legacy application using django 1.4.2 and python-social-auth.
I have the app installed
INSTALLED_APPS = (
...
'social.apps.django_app.default',
...
)
The backends:
AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookAppOAuth2',
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth',
'social.backends.google.GoogleOAuth2',
'social.backends.google.GoogleOpenId',
'django.contrib.auth.backends.ModelBackend',
)
More settings...
SOCIAL_AUTH_FACEBOOK_ID = ''
SOCIAL_AUTH_FACEBOOK_SECRET = ''
SOCIAL_AUTH_ENABLED_BACKENDS=('facebook', 'google')
SOCIAL_AUTH_DEFAULT_USERNAME= lambda u: slugify(u)
And in my root url :
urlpatterns += patterns('',
url('', include('social.apps.django_app.urls', namespace='social'))
But I still get this error:
Template error:
In template /home/matias/Proyectos/apuntes/copias/templates/login.html, error at line 9
9 : <p>Ingresá con tu cuenta de <a class="login facebook" href=" {% url 'social:begin' 'facebook' %} {% if request.GET.next %}?next={{ request.GET.next }}{% endif %}">Facebook</a> </p>
Exception Type: NoReverseMatch at /login
Exception Value: u"'social" is not a registered namespace
I don't know what's missing. As far as I can tell I have everything right.
The quoting in the error messages worries me. But the urls.py is fine so maybe it's django formatting being funny.
Any pointer?
Version missconfiguration. For django lower than 1.5 you need to add:
{% load url from future %}
Right up the template.
I was confused because that's not listed in the section about url dispatching in the docs https://docs.djangoproject.com/en/1.4/topics/http/urls/#defining-url-namespaces.
I also had no idea the load templatetag had a from argument...

ViewDoesNotExist while rendering

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

RequestContext returns 404 error for my imagaes?

I stumbled on a silly situation with Django's RequestContext thing. Here is my question:
I stored all my images in my media/uploads file. In my template I'm simply using :
{% for photo in photos %}
<img src="{{gallery_root}}/{{photo.get_name}}" />
{% endfor %}
My view is :
def gallery_view(request):
photos = Photo.objects.all()
return render_to_response('gallery/sampleGallery.html',{'photos':photos},context_instance=RequestContext(request))
In my settings file :
GALLERY_ROOT = os.path.join(MEDIA_ROOT, "media/uploads")
And i have a contextprocessor file which contains:
from django.conf import settings
def gallery_root(request):
return {'gallery_root':settings.GALLERY_ROOT}
When I open my template, the image's path appears however the server gives 404, the path seems correct but django can not serves them.. So what's the reason that I can not see images on my template ?
The image source appears like this :
<img src="/Users/imperium/Desktop/sample/media/uploads/popo.jpg" />
Hey there, it's probably that your media isn't being served propery.
Try something like this in your urls.py file.
# if we're in DEBUG mode, allow django to serve media
# This is considered inefficient and isn't secure.
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.GALLERY_ROOT}),
)
MEDIA_ROOT is the filesystem path to your media, not the URL path. Building on the suggestion from mongoose_za, your template should look like:
{% for photo in photos %}
<img src="/media/{{photo.get_name}}" />
{% endfor %}
Of course, you can define a new constant in settings.py which corresponds to the URL root you've chosen, and use this both in urls.py as well as in your templates.

NoReverseMatch Error

I keep getting this error for the django login system. Here is part of my urls.py:
(r'^contractManagement/login', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
The exact error I am getting:
Exception Type: NoReverseMatch
Exception Value: Reverse for ''django.contrib.auth.views.login'' with arguments '()' and keyword arguments '{}' not found.
I can't understand why i am getting this error. If you need anything else let me know.
You don't show where you are trying to reverse this URL, but it looks like you have double-quoted it. If you're using the url tag, note that you don't need quotes around the url name:
{% url django.contrib.auth.views.login %}
not
{% url 'django.contrib.auth.views.login' %}
You see that ''the.unknown.view'' is reported including too many qoutes.
It is because the quoted syntax will be valid in Django 1.5 and higher. For Django 1.3 or 1.4, you should activate the future behavior by this line in the template:
{% load url from future %}
which is valid also for Django 1.5.
Example for Django 1.5+
{% url "path.to.some.view" %}
Classic syntax for Django <= 1.4.x (without "future" command) is:
{% url path.to.some.view %}
I would give your url a name (in order to do that, you need to use the url method) Also you should add a trailing slash to all your urls, cause the django CommonMiddleware is going to be doing a 302 redirect on all your urls if you don't:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^contractManagement/login/', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='contract_login'),
)
Then you can use reverse in your code, or url in your templates, and if you ever decide to change the actual url (ie: changedCotractManagement/login/), as long as the name is the same, your code will still be good.
in code:
from django.core.urlresolvers import reverse
reverse('contract_login')
in template:
{% url contract_login %}
Edit: per MrOodles

Is it possible to pass query parameters via Django's {% url %} template tag?

I'd like to add request parameters to a {% url %} tag, like ?office=foobar.
Is this possible? I can't find anything on it.
No, because the GET parameters are not part of the URL.
Simply add them to the end:
<a href="{% url myview %}?office=foobar">
For Django 1.5+
<a href="{% url 'myview' %}?office=foobar">
A way to mix-up current parameters with new one:
{% url 'order_list' %}?office=foobar&{{ request.GET.urlencode }}
Modify your settings to have request variable:
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)
Use urlencode if the argument is a variable
<a href="{% url 'myview' %}?office={{ some_var | urlencode }}">
or else special characters like spaces might break your URL.
Documentation: https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#urlencode
First, a silly answer:
{% url my-view-name %}?office=foobar
A serious anwser: No, you can't. Django's URL resolver matches only the path part of the URL, thus the {% url %} tag can only reverse that part of URL.
If your url (and the view) contains variable office then you can pass it like this:
{% url 'some-url-name' foobar %}
or like this, if you have more than one parameter:
{% url 'some-url-name' office='foobar' %}
Documentation: https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#url
Tried all the above, nothing worked.
My system has:
Python 3.8.10
python3 -m django --version 4.0.3
Here's what worked for me:
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('single/', views.single, name='single'),
]
views.py
def single(request):
url = request.GET.get('url')
return HttpResponse(url)
Calling from .html file
<a href={% url 'single' %}?url={{url}} target="_self">
Broswer URL
http://127.0.0.1:8000/newsblog/single/?url=https://www.cnn.com/2022/08/16/politics/liz-cheney-wyoming-alaska-primaries/index.html
Try this:
{% url 'myview' office=foobar %}
It worked for me. It basically does a reverse on that link and applies the given arguments.