Django: For Loop in Views.py? - django

I want to keep my templates free of any logic - just html. I'm using a "for" loop in index.html to cycle through a list of posts. Here is the loop:
{% for recent in latest %}
<h1>{{ recent.title }}</h1>
<h2>{{ recent.category }}</h2>
{% endfor %}
What I want to do is in my Posts class, grab all the posts, checking that they match certain criterion, then place them in variables which could be sent to the template.
Here is the view (the logic of which I want to eventually move to models.py):
def index(request):
# Get latest five posts
latest_posts = Post.objects.order_by('-published_date')[:5]
# Get a single "top" category post.
top_post = Post.objects.get(category = 1)[:1]
# set up some contexts
top = {'front_post': top_post}
context = {'latest': latest_posts}
return render(request, 'home/index.html', context, top)
Any suggestions?

You're taking the idea of keeping templates free of logic too far. There's a reason template languages provide things like for loops and boolean logic: without them you will wind up breaking the separation of concerns that an MVC framework is trying to enforce. Because what you will wind up with is embedding presentation information in your view logic and that's not what you want. As a simplistic example, consider adding the option of viewing your posts as a text file without adding a second view. If you keep the markup in the templates, it's easy. If you don't, it's not possible.

Related

How to make a for loop break on counter in Django Templates?

How can I make the for product in products loop break after the if condition is fulfilled 3 times. I have been trying to set up a counter but that isn't working... because set is not accepted inside of for loops. Though testing it out a bit more it isn't being accepted anywhere.
When I use set it throws this exception or a variation of it: Invalid block tag on line 11: 'set', expected 'endblock'. Did you forget to register or load this tag?
I am aware that I should put all the logic I'm using Templates for inside of the view and then pass it through the dictionary but it would take too much time to research everything about that and i just want to be done with this.
Honestly I am really tired it is 6am and idk what to do. Thank you for your help in advance. :)
Edit: I know I have to use namespace() for set to be able to propagate across scopes. But set itself is still raising the same exception as above.
Edit2: I thought that django uses jinja2 as it's templating language but it seems like that is not the case. I fixed the mentions of jinja2 as I haven't changed any of the defaults that come with a fresh install of django.
HTML
{% for category in categories %}
<div>
<h5 class="text-line"><span>{{category.name}}</span></h5>
</div>
<!-- Cards Container -->
<div class="shop-cards">
{% set counter = 0 %}
{% for product in products %}
{% if product.category.categoryID == category.categoryID %}
<!-- CARD 1 -->
<div class="card">
<image class="product-image" src="{% static 'images/product-4.png' %}"></image>
<div class="card-category-price">
<h3 class="product-name">{{product.name}}</h3>
<h3 class="product-price">{{product.price}}</h3>
</div>
</div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
You can't (by design).Django is opinionated by design, and the template language is intended for display and not for logic.
You can use Jinja instead.
Or, you can do the complicated stuff in Python and feed the results to the template language through the context. Bear in mind that appending arbitrary objects to a list in Python is a cheap operation. So (in a CBV) something like
context['first_three'] = self.get_first_three( whatever)
...
def get_first_three(self, whatever):
first_three = []
for obj in ...:
if complicated stuff ...
first_three.append( obj)
if len(first_three) == 3:
break
return first_three
BTW you can't (easily?) implement break in Django templating, but you can easily give it the ability to count:
class Counter( object):
def __init__(self):
self.n = 0
def value(self):
return self.n
def incr(self):
self.n += 1
return ''
In the context pass context['counter'] = Counter()
In the template refer to {{counter.value}} as much as you want, and in a conditional where you want to count occurences, use {{counter.incr}}. But, it's hacky, and probably best avoided.
The problem seems to arise due to a misconception of the templating functionality. It is to be used mainly for display purposes and not filtering purposes, and you are facing a filtering problem:
I want to filter the 3 first elements of a list that fulfill a specific condition
is your main issue and templating frameworks will be poor at solving your issue, whereas this is exactly what python and Django's ORM are good at.
Why don't you first filter in Django, then display in template? For example as follows:
...
products = queryset.filter(abc=condition)[:3]
context = Context({ 'products': products })
return HttpResponse(template.render(context))

Django/Haystack - best option to have a listview with search capability

I have an app with a Restaurant model. I'd like to understand what is the best way to put together a view that displays the list of restaurant objects, but also has a search form above that a user could enter parameters to filter the results displayed. If no parameters are entered, all the restaurants should be shown. I'm already using haystack and have a search form, but currently it is on a standalone search.html template. I also have an ListView on a separate template, and I guess I'm looking for an end result that combines these.
I did some reading on line and it's unclear what the best way to do it is:
using just listview from Django with some queryset filtering
combining haystack SearchView with django class based views?
this is my best bet so far - creating a customized version of SearchView from Haystack
ideally, ultimately the search capabilities would include things like allow autocompleting the user's inputs, and dynamically filter the results as the user types.
any thoughts on what the best way is to go about this and any examples out there?
There probably is out there some package that gives you everything automatically, displaying the queryset list and allowing simple adding of a search bar and so on (like the admin site). But I take it you are still a beginner to web development, so I'd strongly suggest you drop the listviews, drop haystack, drop everything, and do it all yourself.
See, they're not bad approaches or anything, but they're like shortcuts. And shortcuts are good only if they shorten the original way, which in your case isn't all that long.
To give you an example, here's a simple approach to displaying a list of items:
views.py
def restaraunt_list(request):
restaraunts = Restaraunt.objects.all().order_by('name')[:100] # Just for example purposes. You can order them how you'd like, and you probably want to add pagination instead of limiting the view number arbitrarily
context = {'restaraunts': restaraunts}
return render_to_response('index.html', context)
index.html:
<ul>
{% for rest in restaraunts %}
<li>{{ rest }}</li>
{% endfor %}
</ul>
That's it. Now it displays it in a list. Now to add a search filter all you need to do is this:
index.html (add this anywhere you want it)
<form>
<input type='text' name='q' id='q'></input>
<input type='submit' value='search!'></input>
</form>
When a user sends the data from 'q' it is sent through GET, and then on server side you add this:
def restaraunt_list(request):
restaraunts = Restaraunt.objects.all()
# filter results!
if request.method == 'GET':
q = request.GET['q']
if q != '':
restaraunts = restaraunts.filter(name__contains=q)
# ordering is the last thing you do
restaraunts = restaraunts.order_by('name')[:100]
context = {'restaraunts': restaraunts}
return render_to_response('index.html', context)
Now, this will work, but from what you wrote I understand you want the search to be live the moment a key is pressed. For that, you'd need to use AJAX (go learn how it works, I'm not gonna delve into it here). As for autocomplete, you should check out jQuery UI.
But, like I said, before jumping ahead and using all those stuff, I suggest you first learn the basics. Go through the django tutorial (if you haven't already), and use the amazingly detailed django-docs every step of the way. When some specific things won't work and you're stuck, come here to Stackoverflow and someone will surely help you. good luck!

Using the Django assignment_tag built-in tag the right way

I'm working on a project in Django.
Earlier today, I discovered the new (Django >= 1.4) assignment_tag. I immediately decided that it was just what I needed EVERYWHERE and threw some logic into one that executed a very simple query against the database and returned the resulting queryset. The function I wrapped takes an argument that allows the invoking context to specify how many results to grab, directly in the template when I am using the template tag.
It is quite convenient - I don't have to update my view when I decide this list should have 5 items, not 3 - but it seems like one of those gray areas where we aren't supposed to tread (i.e. pushing application logic into templates) when writing good, maintainable Django code.
Now, a couple of hours separated from writing the code, I'm wondering if I should scrap the assignment_tag entirely.
Code:
models.py:
class SomeObject(models.Model):
is_active = models.BooleanField(default=False)
(...)
templatetags/myapp_tags.py:
from django import template
from myapp.models import SomeObject
register = template.Library()
#register.assignment_tag
def get_someobjects_list(max_results=0):
queryset = SomeObject.objects.filter(is_active=True)
if max_results == 0:
return queryset
elif max_results > 0:
return queryset[:min(max_results, queryset.count())]
else:
return None
templates/myapp/chunks/someobject_list.html:
{% load myapp_tags %}
{% get_someobjects_list as someobjects_list %}
# or {% get_some_objects_list 5 as someobjects_list %} ... flexible!
{% if someobjects_list %}
<ul>
{% for someobject in someobjects_list %}
<li>
<a href="{{ someobject.get_absolute_url }}">
{{ someobject.name }}
</a>
</li>
{% endfor %}
</ul>
{% else %}
<span>No someobjects exist</span>
{% endif %}
I was really excited to discover these existed - it's convenient for me in this particular case. Now that my excitement over finding a new feature has passed, it seems pretty clear that I'm misusing it. The example given in the Django docs seems like a better application of this - grabbing the string representation of current datetime, something that doesn't require a DB query. My worry is that I'm setting myself up for heartache if I start using this pattern regularly. Following the slippery slope all the way down: I'll end up not even bothering to pass a context to my templates and ALL my DB queries will be hidden away in template tags where nobody would think to look for them.
It seems the code would be cleaner if I just threw out this whole "great idea" I had when I discovered assignment_tags and created a custom model manager instead.
Are there other clean ways of accomplishing this that I am missing? Are manager methods the consensus best way among Django developers?
assignment template tags are especially helpful if you need to get some information into the template context for a few pages of a website, but don't want to (or can't) put the info into every view on the website, and don't want to or can't rely on a context processor.
they basically guarantee that your information will be available in the template.

Django partial template responses

Is it considered correct/ are there any pitfalls in returning partial templates to ajax POST requests?
For example:
if request.is_ajax:
# response is just the form
return render(request, 'contact/fields.html', {'form':form})
The most typical approach is returning JSON and then contructing whatever HTML you need client-side from the JSON data. However, it could be argued that this is mixing presentation with behavior and it would be better to clearly separate out the HTML.
On the flip-side, returning a block of HTML is about as polar-south of "RESTful" as you can get. In pure REST philosophy, the views should return data in a standard and reusable container (such as JSON or XML). Later if you needed to pull the form into an iOS/Android/WP7/etc. app environment rather than a webpage, the JSON/XML will serve you just as well, whereas the HTML is virtually useless.
I can easily see both arguments, and I don't think one is necessarily more right than the other. Ultimately, I think you just have to do what works best for your app and what "feels right" to you. Think in terms of what is more maintainable and extensible for your particular circumstances.
I have no yet tried this with form POST request but very similarly we return partial HTML to AJAX GET request to do page changes without loading the whole page. I think it would work well for form request as well (we are in fact debating at the moment whether to use this approach on a page with multiple different forms).
I think if done right it is not a bad design pattern. We accomplish this by changing which base template is extended based on whether it was an AJAX call.
A simplified example:
### view
base_template = "base.html"
if request.is_ajax():
base_template = "base-ajax.html"
return render_to_response(request, 'page.html', {'base_template': base_template})
### page.html
{% extends base_template %}
{% block main %}new page content{% endblock %}
### base.html
<html>
<!-- complete html page -->
...
{% block main %}this is what changes per page{% endblock %}
...
</html>
### base-ajax.html
{% block main %}this is what changes per page{% endblock %}
I think most of my ajax return responses return DOM elements and not the entire form.
(an example)
...
person = ''' {1} {2}'''.format(p.id, p.first_name, p.last_name)
q = simplejson.dumps({"person":person})
return HttpResponse(q, mimetype="application/json")
The above sends back a simple DOM element to the template and inserts it into a table at the bottom. Sliding in right to left.
If you send back the entire template, the entire screen will flash and won't get any slick animations. That is my understanding anyway.
I have done this for a couple of jQuery Dialogs. The dialog contents are requested by a AJAX request, the contents are rendered on server side and then returned and displayed. So far I have experienced no problems with that.
From personal experience i can say that there is no pitfalls. I just not very good design pattern (not good practice). I used to do that on pretty high loaded project.
I have had the same problem in the year 2023 (question was asked in 2012..). Django still doesn't support rendering a template without invoking the whole chain of template inheritance.
So here's a basic way of rendering partial template:
from django.template import Context, loader
def render_template_to_string(template_name, context=None):
template = loader.get_template(template_name).template
context_instance = Context(context or {})
with context_instance.bind_template(template):
return template.nodelist.render(context_instance)
And your (partial) template can be as simple as:
<ul>my partial list
{% for opt in options %}
<li>{{ opt }}</li>
{% endfor %}
</ul>
You then invoke it by e.g.
from django.http import HttpResponse
resp = render_template_to_string(
"path/to/partial/html", {"options": range(10)}
)
return HttpResponse(resp)
FYI you might want to add support for some node exclusions, error handling, or better flexibility of what gets passed to render_template_to_string.

What's the best way to allow an infinite amount of foreign keys to the same model?

I'm making a forum with django right now, and I want it so that anyone can comment on anyone else's comment. Right now I have a foreign key in my 'Comment' model that points back to itself so I can get the parent comment easily from any comment.
In my theory this worked great, because from any comment I could get all of its child comments, and then just keep branching down from there to get every single child comment. However I'm having trouble actually implementing this when it comes to getting the data from the view to the template.
I want it to be possible to have an infinite number of child comments, because who knows how long a discussion will last and I don't want to arbitrarily limit it. The problem I'm having is would you get all of those comments from the view to the template without losing their relationship to their parent comment?
Currently this is what the psuedocode for my code looks like:
#the view
def comment_page(request, forum, comment_id):
#this is the main comment that all others will stem from
main_comment = Comment.objects.get(id=comment_id)
children_comments = main_comment.comment_set.all()
#the template
{% for comment in children_comments %}
<p class='comment'>{{comment}}</p>
{% endfor %}
Obviously I'm not even trying to get all the child comments here, it just gets child comments of the very first post. What I don't understand is how can I then go through each of these child comments and then get all of theirs, and keep doing that for each new comment?
It makes the most sense to do it in the view since I am able to use Django's QuerySet API in there, but I don't see how I would be able to pass all of the comments to the template without losing their relationship to their parent. The only idea I can think of is to go through all of the comments in the view and build up a string of html that I just pass and simply display in the template, but that seems like a horrible idea because it'd be dealing with template related stuff in the view.
You might want to look into using a MPTT such as django-mptt
this can be implemented by a custom filter with an inclusion_tag that includes itself but causes a lots of queries to your db:
#register.inclusion_tag('children.html')
def comments_tree(comment):
children = comment.comment_set.all()
return {'children': children}
# children.html
<ul>
{% for child in children %}
<li> {{ child }}</li>
{% if child.comment_set.count > 0 %}
{% comments_tree child %}
{% endif %}
{% endfor %}
</ul>
# your template
{% comments_tree comment %}
This older question is probably of interest:
How can I render a tree structure (recursive) using a django template?
Edit: to future readers, don't do this as the inner for loop's comment variable does not substitute the outer comment variable during the loop execution, leading to infinite recursion. /Edit
If you need a recursive tree structure in your HTML page (i.e. a bunch of nested <div> tags), you can write a recursive "comment" template.
Sample: (untested)
{# comment.html #}
<p class='comment'>{{ comment.text }}</p>
{% if comment.children %}
{% for comment in comment.children %}
{% include "comment.html" %}
{% endfor %}
{% endfor %}
The for loop binds the comment template variable to each child before including itself.
Performance note: Unless your comment sets are often short, this will probably be very slow. I recommend that you make your comments non-editable and cache the result!
Alternate solution: If you don't need the recursive HTML <div> tags, you can write a generator that performs a pre-order traversal of the structure and yields (depth, comment) pairs. This would likely be far more efficient in rendering speed.