Django Url does not work - django

I am trying to obtain a url to a view that renders an image so I can use it in an img tag with href.
But my {% url viewname object_id %} is not working. Here are the specifics:
my urls.py:
hydrourlpatterns = patterns('',
url(r'^graphs/$','hydro.views.graphs',name='graphs'),
url(r'^graphs/new/$', 'hydro.views.add_graph', name='add_graph'),
url(r'^graphs/(?P<graph_id>\d+?)/$', 'hydro.views.single_graph', name='graph_detail'),
url(r'^graphs/graphImage/(?P<graph_id>\d+?)/$', 'hydro.views.render_graph', name='graphImage')
)
my template(url: localhost/graphs/(graph_id)/):
{% extends "subpage.django" %}
{% block content %}
{% if graph %}
<h3> {{ graph.name }} </h3>
<h1> {% url 'graphImage' graph_id %} </h1>
{% endif %}
{% endblock %}
The error I keep getting is ViewDoesNotExsist.
Could not import hydro.views.add_site.
View does not exist in module hydro.views.

You use hydro.views.add_site somewhere else in your urls.py. Comment this url line or create add_site view in the hydro.views.
EDIT: You don't pass graph_id variable to the template so change {% url %} call to:
{% url 'graphImage' graph.id %}

Related

{% url ... %} templatetag in Django included template not seeing variable

I'm experiencing strange behaviour in an included template which I can't figure out.
urls.py
urlpatterns = (
path(
"items/",
views.list_view,
name="list-view",
),
path(
"item/<int:pk>/",
views.detail_view,
name="detail-view",
),
)
views.py
def list_view(request):
items = Item.objects.all()
return render(request, "parent_template.html", context={"items": items})
def detail_view(request, pk):
item = get_object_or_404(Item, pk=pk)
return render(request, "detail_template.html", context={"item": item}
parent_template.html
{% for item in items %}
Parent: {{ item.pk }}
{% include 'child_template.html' %}
{% endfor %}
child_template.html
Child: {{ item.pk }}
URL: {% url 'detail-view' item.pk %}
I get a reverse error:
Reverse for '/test/url/<int:pk>/' with arguments '('',)' not found. 1 pattern(s) tried: ['test/url/(?P<pk>[0-9]+)/\\Z']
If however I remove the {% url ... %} template tag, it renders correctly and shows:
Parent: 1
Child: 1
So it's clear that item is in the context, but for some reason it isn't being passed to the templatetag.
I have also tried variations like:
{% for item in items %}
{% with new_item=item %}
{% include 'child_template.html' %}
{% endwith %}
{% endfor %}
Any ideas?
I am using Django 3.2.12
I just found the error - I was looking in the wrong place. My complete code looked like this:
parent.html
<!-- {% include 'child_template.html' %} -->
{% for item in items %}
{% with new_item=item %}
{% include 'child_template.html' %}
{% endwith %}
{% endfor %}
I didn't pay attention to the HTML comment at the top of the template. Obviously Django is still rendering the code on the server side and at that point does not have item in its context.

How to Use Custom Template Tag in Combination With Django's Built-in "with" Tag?

I have this simple tag:
myapp/templatetags/my_filters.py
#register.simple_tag
def get_bookmark_object(content_type, object_id):
return Bookmark.objects.get(content_type=content_type, object_id=object_id)
In my template, I want to be able to do this:
{% load my_filters %}
{% with object as bookmark %}
{% with bookmark_object=get_bookmark_object bookmark.content_type bookmark.object_id %}
{% if bookmark.content_type.model == 'post' %}
{% include 'content/post/object.html' with object=bookmark_object user_bookmark=bookmark %}
{% elif bookmark.content_type.model == 'note' %}
{% include 'content/note/object.html' with object=bookmark_object user_bookmark=bookmark %}
{% endif %}
{% endwith %}
{% endwith %}
I get the error:
TemplateSyntaxError at /my-page/
'with' received an invalid token: 'bookmark.content_type'
My question is:
How do I use my custom get_bookmark_object template tag in a with statement? An example with code would help me clarify a lot.
Reference:
Django's with built-in
What you defined is a template tag, you can assign the value produced by the template tag with an {% … as … %} tag:
{% get_bookmark_object bookmark.content_type bookmark.object_id as bookmark_object %}
…

Django - Custom tag not working

I want to pass a model to template base.html.
I read about custom tags, and tried to execute this. It is not throwing any error, but is not working too.
My code:
base.html:
{% load staticfiles %}
{% load tags %}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul class="dropdown-menu" role="menu">
{% for league in get_my_leagues %}
<li> ddddd {{ league.league_name }}</li>
{% endfor %}
</ul>
{% block content %}
{% endblock %}
</body>
</html>
Now, tags.py:
from django.template import Library
from login.models import League
register = Library()
#register.inclusion_tag('base.html')
def get_my_leagues():
return League.objects.all()
register.tag('get_my_leagues', get_my_leagues)
When you use {% for x in y %}, this expects that y is a context variable in your template, not a template tag.
What an inclusion tag does is that it renders a template (the one you pass as argument to the inclusion_tag decorator), and inserts the result where the inclusion tag is used.
You probably want to register get_my_leagues as a simple tag instead (or an assignment tag, if you're using Django older than 1.9), and use it like this:
{% get_my_leagues as my_leagues %}
{% for league in my_leagues %}
...
{% endfor %}
guys.
I'm here just to tell that i found a solution for my problem. I'm using Context Processors to do this job.
Thank you all for answers!

Django 1.6 - parse template tags after import/parse from view

Firstly, I'm relatively new to Django, so forgive me if there's some fundamental misunderstanding on my part.
I'm looking to parse some Django template tags that are imported as a part of a Django render. The end issue I'm seeing is the HTML/JS portions are being correctly called and displayed, but the last Django tags are being rendered as plain text on the page. I realize it's because I'm rendering the view before one step too early, but I'm not sure how to go about this correctly.
Here's the basic call stack (simplified):
template1
{% extends base.html %}
{% block main_content %}
{{ block.super }}
<div id="col1" class="chart-col" style="float: left; width: 33%;">
{% block col1 %}
{% endblock col1%}
{% endblock main_content %}
template2:
{% extends template1.html %}
{% block main_content %}
{% for DATA in DATALIST %}
{{ DATA|safe }}
{% endfor %}
{% endblock main_content %}
python code that generates desired Django / HTML for the above DATALIST in template2:
def chartdisplay(block_var, othervars):
text = "{% block block_var %} \n {{ block.super }} \n"
text += "<html to generate data display goes here>"
text += "{% endblock block_var %}
return text
the above python is passed to the Django View.py:
def dataview(request):
datapull = model.object.filter(**kwargs) #generic data pull
#date-time handler
dthandler = lambda obj: (
obj.isoformat()
if isinstance(obj, datetime.datetime)
or isinstance(obj, datetime.date)
else obj)
data = {'data': datapull}
chart_html = [
chartdisplay(block_var="col1", other_unique_vars),
chartdisplay(block_var="col2", other_unique_vars),
chartdisplay(block_var="col2", other_unique_vars),
chartdisplay(block_var="col3", other_unique_vars)
]
context = {'data', jsondump(data, default=dthanlder), 'charts': charts_html)
return render(request, 'path/to/template2.html', context)
Now, the main issue is the resulting HTML that is displayed displays the HTML and JS fine, but has the Django template tags exposed as text and does not direct the chartdisplay into the desired divs. E.g. template2.html is viewed as:
{% block col1 %} {{ block.super }}
<html/D3 chart is displayed fine>
{% endblock col1 %}
{% block col2 %} {{ block.super }}
<html/D3 chart is displayed fine>
{% endblock col2 %}
{% block col2 %} {{ block.super }}
<html/D3 chart is displayed fine>
{% endblock col2 %}
{% block col3 %} {{ block.super }}
<html/D3 chart is displayed fine>
{% endblock col3 %}
I've tried a few various band-aid fixes but I'd rather just understand how to do this properly. The one thing I've tried but am probably misunderstanding is, before the return render step:
def dataview(request):
...
rendered = render_to_string('path/to/template12.html', context, context_instance=RequestContext(request))
return render(request, 'path/to/template2.html'/, rendered)
Thanks for you help. Please let me know if any clarification is needed!
You don't have to use render, it's just a shortcut that takes a request, template name and context, and returns an http response with the rendered context.
That's not what you want in this case. You have a template string rendered that you wish to render. The low level API to render a template is explained here in the docs.
from django.template import Context, Template
from django.http import HttpResponse
def dataview(request):
...
rendered = render_to_string('path/to/template2.html', context)
template = Template(rendered)
return HttpResponse(template.render(Context(context)))
You may have to use the verbatim tag so that your blocks and extends tags are not evaluated when you call render_to_string on the first template. For example
{% verbatim %}
{% extends template1.html %}
{% block main_content %}
{% endverbatim %}
{% for DATA in DATALIST %}
{{ DATA|safe }}
{% endfor %}
{% verbatim %}
{% endblock main_content %}
{% endverbatim %}

conflict between User and user.socialaccount in django-allauth

I have done this tutorial as it explained here:
and here
but there is some points that i can not understand.
When i log in using a facebook account i can get access also easily to my admin page and i want it to be happened (because it is not secure), so is there a way to fix that ?
If i want to bring that registred user to another template, i can do it only whith direct_to_template method in my url dispatcher, here is an example:
url(r'^tags$', direct_to_template, {'template' : 'user.html' }),
is there another way to do it.
Finally to be more clear, here is some snippets of my project:
urls.py
urlpatterns = patterns('',
#All Auth URLS
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/profile/', direct_to_template, { 'template' : 'profile.html' }),
#nav urls
url(r'^$','fb.views.home', name="home"),
url(r'^tags$', direct_to_template, {'template' : 'tags.html' }),
views.py
def home(request):
return render_to_response("base.html", locals(), RequestContext(Context))
base.html
.....
{% block body %}
{% block content %}
{% if user.is_authenticated %}
{{ user.username }} <p> you are logged in </p>
<p><a href="/accounts/logout/" >Logout </a></p>
{% else %}
<p> you are not authenticated : </p>
<a href="/accounts/facebook/login/" >Login with Facebook </a>
{% endif %}
{% endblock content %}
{% endblock body %}
...
profile.html
...
{% block content %}
{% if user %}
<h1>Welcome, {{user.first_name}}</h1>
<p>Following is the Extra information that facebook has provided to allauth:</p>
{% for account in user.socialaccount_set.all %}
<p>First Name: {{ account.extra_data.first_name }}</p>
<p>Last Name: {{ account.extra_data.last_name }}</p>
<p>Profile Link: {{ account.extra_data.link }}</p>
{% endfor %}
{% endif %}
Go to tags
{% endblock content %}
{% endblock body %}
tags.html
{{user.socialaccount_set.all.0.get_avatar_url}} <br/>
{{user.socialaccount_set.all.0.uid}} <br/>
{{user.socialaccount_set.all.0.get_provider_account }} <br/>
Finally thanks in advance for your help .
The secrect is:
After logging in, the user was hiding in the request object, so view shoukd be like this:
def home(request):
user = request.user
return render_to_response("base.html", locals(), RequestContext(Context))
Now, the problem is resolved, but i wonder why the Context User object was anounymous.
i am asking this question because that last user object woiuld have the same value of the request user in a simple authentication