Get first item of QuerySet in template - django

In my blog app I want to display a list of blog posts and the first image connected to this post. Now I do it this way:
{% for image in entry.image_set.all|slice:"1" %}
<img src="{{ image.get_absolute_url }}">
{% endfor %}
Is there a template shortcut I don't know about, or maybe I should just write my own Manager?

Not any shorter, but you could use first:
{% with entry.image_set.all|first as image %}
<img src="{{ image.get_absolute_url }}">
{% endwith %}

Since Django 1.6 you can do
<img src="{{ entry.image_set.first.get_absolute_url }}">

You also can do:
entry.image_set.all.0 in your template.

I was having the following queryset I just want to retrieve first element from it in jinja template.
<QuerySet [<StudentDetails: StudentDetails object (1)>, <StudentDetails: StudentDetails object (2)>]>
Solution
{{ StudentDetails.first.name }}
StudentDetails is my model

Related

Get a random object of a Wagtail page model but not the current one

So I have this template context processor:
from cases.models import CasePage
def random_case(request):
case = CasePage.objects.live().order_by('?')
return {'random_case': case}
And in the template I do this:
{% for entry in random_case %}
{% if request.get_full_path != entry.get_url %}
{% if forloop.first %}
<a class="ajax-link project-next" href="{{ entry.get_url }}">
<div class="nav-project-title">{{ entry.title }}</div>
<div class="nav-title">next</div>
</a>
{% endif %}
{% endif %}
{% endfor %}
And this works but the problem is sometimes the object is the same as the page so nothing is displayed. It would be great if that one would be skipped in favour of the next entry. And it's also too much logic in the template for me. What would be the best way to move this logic into the context processor and make it work?
Make random_case a method of CasePage, and filter out the case with an ID equal to self.
class CasePage(Page):
# ...
def random_case(self):
return CasePage.objects.live().exclude(id=self.id).order_by('?').first()
You can then refer to this method within your template as page.random_case - bear in mind that a new random choice will be made on each call, so you probably want something like {% with page.random_case as case %}.

How to set href value in html using python

I have been trying to solve this problem: i want to set url to html a tag using loop. I tried this way. But it gives me error which is "Reverse for 'i.menuResolve' not found. 'i.menuResolve' is not a valid view function or pattern name".
In case, "i.menuResolve" returns url which is '/sales/profile' etc.
{% for i in userMenus %}
<li>
<a href="{% url 'i.menuResolve' %}" ></a>
</li>
{% endfor %}
Please help if anybody knows this error?
If you have a method or property that returns a URL, you don't need to use Django's {% url %} template tag. That template tag passes the arguments to Django's reverse() function, but you don't need to do that if you've already got the URL.
Give this a try:
{% for i in userMenus %}
<li>
<a href="{{ i.menuResolve }}" ></a>
</li>
{% endfor %}

FileField/ImageFIeld URL isn't giving me a HTTP URL

I have this code, where partner.logo is an ImageField in the Partner model.
{% for m in matches %}
<img src="{{ m.partner.logo }}" alt="" />
<h2>{{ m.partner.name }}</h2>
<p>{{ m.reasons }}</p>
<p>{{ m.partner.profile }}</p>
{% endfor %}
Now, the Django documentation says if you go m.partner.logo.url, you'll get a URL to the file. However, all I got was
<img src="/Users/shinichi/Dropbox/source/blastoise/uploads/road-sky-clouds-cloudy.jpg" alt="" />
and that actually is the same string that I'd get from m.partner.logo. This isn't a URL, and it's not helping! I was expecting something like http://127.0.0.1:8000/uploads/road-sky-clouds-cloudy.jpg. Am I missing something?
You probably have some problems with the MEDIA_URL and the MEDIA_ROOT on the settings.py (please take a look here) as pointed by #domino. I've written an example to you here. There is one important detail too when referencing the logo URL, you probably will need to do something like this. I mean:
{% for partner in partners %}
<img src="{{ partner.logo.url }}" alt="" />
<h2>{{ partner.logo }}</h2>
{% endfor %}
Remember to add these lines on your urls.py to help you with serving the media resources on development, it always helps a bit with.
Hope that it can help you mate.
It really depends on what you've set your MEDIA_ROOT to in proj/settings.py file. In your models.py file, you can designate the upload_to argument in the FileField. Here's the documentation on that.
You can designate other places. The most popular is Amazon S3. I set my template to read
<img src="https://s3-us-west-2.amazonaws.com/fsbo-facebook/{{ house.photo }}" alt="{{ house.title }}">
Hope this helps.

How to get label tag in html from django form

{% for field in columnMetaData %}
{{field}}
{% endfor %}
Code above only displays <input>...</input>
But how to get and <label></label>, because labels exists in columnMetaData
I forgot to say that columnMetaData is ModelForm
NEW UPDATE
Just another question. Is there way to add class in each {{field}} ?
And field to be like this: <input type="" class="something" ></input>
You could use attrs to set classes for your field. Usage: field=forms.CharField(attrs={'class': 'some-class'})
Like that :
{% for field in columnMetaData %}
{{ field.name.label }}
{% endfor %}

Django template if statement always evaluates to true

This seems like it should be pretty straightforward, but for some reason I am unable to solve this problem. I'm using Django 1.4. I am trying to do a basic check to see if a list QuerySet is empty or not during template rendering, but the if statement I'm using seems always to evaluate to true.
I have a Django template that reads:
{% extends 'includes/base.html' %}
{% if object_list %}
...
{% block data %}
{% for object in object_list %}
...
{{ object.create_date }}
...
{% endfor %}
{% endblock data %}
...
{% endif %}
'base.html' has the block:
<body>
{% block content %}
...
<div class="row-fluid">
<div class="span12">
{% block data %}
<div align="center"><i>No data.</i></div>
{% endblock data %}
</div><!-- span12 -->
</div><!-- row -->
{% endblock content %}
...
</body>
The view function generating the QuerySet is here:
def barcode_track(request, model):
query = request.GET.get('barcode_search', '')
object_list = model.objects.all()
if query:
object_list = model.objects.filter(barcode__icontains=query)
return render_to_response('barcode_track/barcode_list.html',
{'object_list': object_list, 'query': query},
context_instance=RequestContext(request))
Which is called via this form:
<form id="barcode_search_form" method="get" action="" class="form">
<input type="text" name="barcode_search" value="{{ query }}" />
<button type="submit" class="btn">Search</button>
</form>
And the urls.py line:
urlpatterns = patterns('barcode_track.views',
url(r'^$', 'barcode_track', {'model': Barcode},
name="barcode_track"),)
The idea is that results will only be presented if they exist in object_list, and otherwise the parent block will remain unaltered. I have tried changing the name of object_list, and I have printed {{ dicts }} to the page to ensure that object_list is, in fact, empty (which it is). I am not using a generic view, although I realize that the name suggests as much. I have actually had this trouble in a different app I wrote using similar logic, so I must be doing something systematically incorrectly.
What am I missing here?
You can't wrap control flow tags like if around a block. Your problem is that the child template's definition for block data is being used simply because it's there.
You can fix it by placing the if tag inside block data. If you want to inherit the parent's contents when the list is empty, add an else case that expands to {{ block.super }}.