python-social-auth template url to jinja template url - django

How can i convert this django url tag
{% url "social:begin" "github" %}
to the proper jinja url tag? I have already tried
{% set myurl=url("social:begin", "github") %}
and then use the {{url}}
but i get an
ImportError at /login/
No module named github
My settings.py:
UTHENTICATION_BACKENDS = ('social.backends.github.GithubOAuth2',)
SOCIAL_AUTH_GITHUB_KEY = '75ba4983720f9852c22a'
SOCIAL_AUTH_GITHUB_SECRET = '7e43083e9ee92bd95ad195064f3aaa91704cbfe0'
INSTALLED_APPS = [
'social.apps.django_app.default',
]
and my urls.py:
.....
i18n_urls = [
url(r'^$', 'zerver.views.home'),
url('social-auth/', include('social.apps.django_app.urls', namespace='social')),
.....

At first, you have to add reverse() to jinja enviroment as described here.
So, after that you can use in your template:
{{ url('social:begin', args=['github']) }}

Related

Django & Jinja2 templates using {{ url() }}

I am trying to figure out how to pass my user_id within my html using jinja's {{ url() }}, using urls that don't need any id like /dashboard/ work fine but I need to pass an id to this- example: /user/3 . I have tried the following with no success:
{{ url('detail') }}
{{ url('detail', user_id=User.id) }}
{{ url('detail', User.id) }}
Here's part of my views and html:
views.py
urlpatterns = [
path('dashboard/', dashboard, name='dashboard'),
path('user/<int:user_id>/', detail, name='detail'),
]
dashboard.html
{% for User in all_users %}
{{ url('detail') }}
{% endfor %}
Any help on this would be appreciated, thanks
I found a solution:
{% for User in all_users %}
{{ url('detail', args=[User.id] )}}
{% endfor %}
This also works:
{% url 'detail' user.id %}
Then, in views.py, your corresponding function should receive user_id as an argument (internally user.id becomes user_id).
Django now has official backend support for Jinja2 - I'm guessing you were using django-jinja which provides an implementation of the url function but it's fairly straightforward to integrate Django and Jinja now without adding any additional dependencies (besides Jinja2).
First, configure your TEMPLATES in your settings file and add a dictionary entry with the jinja2 backend:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'APP_DIRS': True,
'OPTIONS': {
'extensions': [<custom extensions if any>]
'environment': 'yourapp.jinja2.environment',
...
},
},
...
]
The key part of this is the environment setting. The examples suggest creating a jinja2.py file in your app directory and defining an environment function there that you'll set to a function that returns a Jinja2 Environment, e.g.,
# example yourapp/jinja2.py
from django.conf import settings
from django.urls import reverse
from django.templatetags.static import static
from jinja2 import Environment
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': static,
'url': reverse,
'settings': settings,
...
})
return env
Here we are binding Python functions (and Django things) to be made available in our Jinja2 environment, so now static in a jinja template can be called static(...) and invoke the Django static function defined in django.templatetags.static, and url is bound to the Django reverse function so url('detail', args=[user.id]) should work. If you prefer a signature like {{ url('detail', pk=123) }} without generating an invalid arguments error you can define your own function:
def jinja_url(viewname, *args, **kwargs):
return reverse(viewname, args=args, kwargs=kwargs)
and bind 'url': jinja_url in your TEMPLATES settings instead.
It's also important to note that Django looks for your jinja templates in a jinja2 directory under your app dir, not the templates directory.

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...

How can I get {% url logout %} to work in my Django template?

My Django app's site-wide urls.py file looks like this:
urlpatterns = patterns('',
url(r'^$', include('myApp.urls')),
url(r'^admin/', include(admin.site.urls)),
url (
r'^accounts/register/$',
RegistrationView.as_view(form_class=extendedRegistrationForm),
),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^', include('myApp.urls')),
)
I also have a urls.py specific to myApp but I have not shown that here because I don't think it's relevant.
In my template file, I have this:
{% url logout %}
It gives me this error:
'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.
When I change the template to:
{% url 'logout' %}
It gives me the following error:
Reverse for 'logout' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
How do I put a link to logout in my view?
Add a logout url like this:
url(r"^logout/$", "django.contrib.auth.views.logout_then_login",
name="logout"),
The correct template syntax is:
{% url 'logout' %}
You didn't include django.contrib.auth's URLs in your urls.py, so there is no logout URL.
Try adding something like
url(r'^auth/', include('django.contrib.auth.urls')),
In django 3.0 {% url 'admin:logout' %} works perfect.

NoReverseMatch in render_to_response with django-social-auth

I would like to make just a page that has link to login to twitter/facebook/google with django-social-auth.
but I get a error NoReverseMatch: Reverse for '' with arguments '(u'twitter',)' and keyword arguments '{}' not found.
def index(request):
ctx = {}
return render_to_response('index_before_login.html', {}, RequestContext(request))
index_before_login.html is following
<li>Enter using Twitter</li>
urls.py is following
urlpatterns = patterns('',
url(r'^$', 'lebabcartoon.views.index'),
#url(r'^socialauth_', 'lebabcartoon.views.index'),
url('', include('social_auth.urls')),
my environment is
Django ver1.5
Python Version: 2.7.3
django-social-auth: 0.7.5
anyideas?
Wrap url name in quotes
{% url 'socialauth_begin' 'twitter' %}
To save someone using the new python-social-auth and django > 1.4
Use this :
{% url 'social:begin' 'twitter' %}
I had a similar problem, try adding the following to the url.py file in your project.
url(r'auth/', include('social_auth.urls'))
And also make sure your url parameters are wrapped in quotes like so.
{% url "socialauth_begin" "twitter" %}

Django 0.96 and url

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 %}