I'm new to Django and I'm having a somewhat hard time understanding how to connect all of the different pieces together. All of the tutorials I've read on Django templates don't explain how to connect all of the pieces.
I have created my base template called base.html. I have a couple functions inside my views.py class that do specific things. Now I want to create pages that inherit from base.html and display information with respect to each function. So say I want action1.html to call the action_one function and action2.html to call the action_two function. I don't really get how to do this. Any help would be appreciated.
sorry for pasting image but this can help you understand how the flow goes:
there are lots of things going on but i didnot draw them so you can see how the basic flow goes.
for the red part, you can use render_to_response as Thomas says. but i would use render as Kevin does.
here the difference:
render() is the same as a call to render_to_response() with a
context_instance argument that forces the use of a RequestContext.
hope this helps a bit
You're misunderstanding how Django templates and views interact: in Django, views render templates, not the other way around (i.e. templates do not call views).
One example of a view rendering a template is the render_to_response helper function.
As for what defines what view is called when a given URL is accessed, this is your URL configuration.
The following is probably where you want to start here:
In your URL configuration, map the /action_one/ URL to the action_one view.
In your action_one view, render the action_one.html template
Hopefully this code example helps lay it out...
urls.py
url(r'^action1/$', 'yourapp.views.action1'),
url(r'^action2/$', 'yourapp.views.action2'),
views.py
def action1(request):
return render(request, 'action1.html')
def action2(request):
return render(request, 'action2.html')
base.html
<html>
...stuff...
<body>
{% block action %}
{% endblock action %}
</body>
</html>
action1.html
{% extends base.html %}
{% block action %}
... action1 html stuff ...
{% endblock action %}
action2.html
{% extends base.html %}
{% block action %}
... action2 html stuff ...
{% endblock action %}
Related
I'm building a site where users can view their posts Like this. After building the quizzes portion, I tabbed to "blogs" where I realized I needed to import the blogs template to use it.
I'm using the quiz template already like this
{% extends '../main/base.html' %} {% block title %}View Quizzes{% endblock %} {% block content %}
but I need to access the blog template as well. How can I do this? Thanks!
You can include the blog template into the main one like:
{% include "path/to/blogs.html" %}
It's best to have a main template which includes blogs, quizzes... (instead of inheritance)
You don't need django to do this.
I have two blocks that call the same method with same variables. I want to call the method only once, but the result is then outsite the scope of the block tags. I've tried calling this method in the parent template header.html and with a with tag, but nothing seems to work.
This is the layout:
{% extends "header.html" %}
{% load navigation_tags %}
{% block header %}
{% get_section site=site as section %}
{% include "foobar.html" with section=section %}
{% endblock header %}
{% block navigation %}
<nav>
<div class="container">
{% get_section site=site as section %}
{% navigation section.slug %}
</div>
</nav>
{% endblock navigation %}
navigation_tags.py
#register.assignment_tag
def get_parent_section(site):
if site.id == settings.FOOBAR_SITE_ID:
section = Section.objects.get(id=settings.FOOBAR_SECTION_ID)
else:
# This is also a section instance.
return site.default_section
As mentioned by 2pacho in another answer and Fernando Cezar in a comment, the easiest way to share values between different sections is to set it in the template context. If you are using the render shortcut function, you can pass a dict as the context parameter to add a value to the rendering context of the template. That would be a good place to add it and this would be the easiest place to put it.
return render(request, 'template.html', {'section': get_parent_section(site)})
However, if for some reason, you can't include it in the context, you can use a decorator to add memoization to your function, so that it will cache the computation results and return it immediately when called with the same parameters. You can use functools.lru_cache to do so, or it's Django backport at django.utils.lru_cache.lru_cache if you are using Python 2.x.
#register.assignment_tag
#functools.lru_cache()
def get_parent_section(site):
if site.id == settings.FOOBAR_SITE_ID:
section = Section.objects.get(id=settings.FOOBAR_SECTION_ID)
else:
# This is also a section instance.
return site.default_section
I wouldn't call a method outside .py . Think that this is using Jinja2 templates,
it's powerful but not in the way that the backend can be.
What I recommend you doing in this case is to generate a context for the template and use this variables there.
Would be as simple as adding it to your context where it's being generated.
context['site_parent'] = get_parent_section(site)
Think that Jinja2 (html) has to be as simple as possible and that can help you with basic coding and time saving (like loops to print the exact same information or show and hide code depending on the context) but I would keep it as simple you can when rendering.
If you would like you can read official django website about templates https://docs.djangoproject.com/en/2.0/topics/templates/
But from my expirience I would keep the method calls in the views.py
I am new to django and I misunderstand how to use templates.
I have a a file called base.html which I see as a parent to hello.html.
In hello.html I have this syntax:
{% extends "base.html" %}
{% block hello %}
<h1>hello</h1>
I should see this template. This is the hello.html template.
{% endblock %}
In base.html I have this syntax:
{% block hello %}{% endblock %}
It is my understanding that django should render hello.html inside of base.html
When I deploy my two html files, django ignores my syntax.
Question: How to render hello.html in base.html?
The files are visible inside of github:
https://github.com/danbikle/sof1231/blob/master/hello/templates/base.html
https://github.com/danbikle/sof1231/blob/master/hello/templates/hello.html
Also I deployed them to heroku with these commands:
heroku create sof1231
git push heroku master
You can see base.html deployed to https://sof1231.herokuapp.com
Again,
How to render hello.html in base.html?
To render a template in another template, you use include:
base.html
{% include 'hello.html' %}
Your templates are designed to work with inheritance, and there is nothing wrong with the simplified templates that you show in your question (I didn't check those on github).
I think that your problem might be caused by your view rendering the base.html template, when it should instead be rendering the hello.html template. You should add your view code to your question so that this can be verified. Your view code should be something like this, which renders the child template hello.html:
def hello(request):
template_variables = {'a': 1, 'b': 2}
return render(request, 'hello.html', template_variables)
Another answer (which you have accepted) recommends using include. I don't think that include is the correct approach.
There is a difference between inheriting from a base template and simple inclusion of content from another file. One important benefit of template inheritance is that you can add common content (e.g. menu, side bars, footers, etc.) to a "base" template and then inherit from that base in child templates without duplicating the common content for each page. Another benefit is that the child templates can override content in the base templates, e.g. <title>. This allows you to markup areas of your layout in the base template (using block) and then override the content of the block with other content. This is not possible with a simple include.
I'm working on a simple blog app in Django, and i'm having trouble figuring out how to dynamically generate the five most recent posts in a side bar. Each of my views are class based and they extend a generic template, each view maps to one template which I believe is the correct way to do it. I've looked for a way to do this using template tags, but it seems Django doesn't like you to put any logic inside of your templates.
The problem I believe is that I want this to exist within my base.html because I want the recent posts to be displayed site-wide, is a view even supposed to map to your base.html or does that cause problems, i'm pretty new with this. I don't know how to approach this, whether i'm supposed to create a new view for base.html or if I should use my template tags, or if I should extend an existing view(but if I do that it won't be site wide?).
I essentially want the following(they're ordered in reverse chronological order)
{% for post in post_list[:4] %}
{{ post.title }}
{% endfor %}
You can use a template tag. More specifically, an inclusion tag is what you need. This allows you to insert a rendered snippet anywhere inside your template via a small view-like piece of code.
For example, create a templatetags/blog_tags.py file (it's important that you create the templatetags folder within your app; Django searches for them here by default) in your blog app and add the following:
from django import template
register = template.Library()
#register.inclusion_tag('blog/snippets/recent_posts.html')
def render_recent_blogposts():
return {
# This is just an example query, your actual models may vary
'post_list': BlogPost.objects.all().order_by("published_on")[:4]
}
now create a blog/snippets/recent_posts.html template (it can be anywhere as long as it mathecs the #register.inclusion_tag(...) above.):
<ul>
{% for post in post_list %}
<li> {{ post.title }}</li>
...
{% endfor %}
</ul>
finally, in your original template, you can now render your template tags:
<aside>
{% load blog_tags %}
{% render_recent_blogposts %}
</aside>
How can I get the full name of the current view (my_app.views.index) in a template in Django 1.5?
With forms, I have an object called "view" in the template which I read using a template tag.
But with DetailViews I doesn't see anything similar.
Is there a way using a custom template processor?
Thanks
EDIT
Situation 1:
I retrieve a page, for example '/foo/bar/5/edit'.
Django will call 'foo.views.editbar' with pk=5.
This view renders an template 'foo/bar_form.html'
Situation 2:
If I retrieve '/foo/bar/new'
Django will call 'foo.views.newbar'
This view renders the same template as above ('foo/bar_form.html')
How can I check in this template 'foo/bar_form.html', from which view it has been rendered?
The result should be one of
'foo.views.editbar'
'foo.views.newbar'
Type just in view
{% with request.resolver_match.view_name as view_name %}
...
{{ view_name }}
...
{% endwith %}
I'm not sure I completely understand the requirement, but take a look at inspect.stack.
inspect.stack()[1][3]
Just set attribute to request object in view:
setattr(request, 'view', 'app.views.func')
and check this in template:
{% if request.view == 'app.views.func' %}
do something
{% endif %}
It worked for me.