Random image selector with Wagtail and Django - python

I am trying to get my homepage in Wagtail to show a random image. I followed the Wagtail start guide and tried to incorporate this hack in the template, but I'm getting an error.
home/models.py
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.core.models import Page, Orderable
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel,InlinePanel
from wagtail.images.edit_handlers import ImageChooserPanel
class HomePage(Page):
body = RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel('body', classname="full"),
InlinePanel('home_images', label='HomePage Images'),
]
class HomeImages(Orderable):
page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='home_images')
image = models.ForeignKey(
'wagtailimages.Image', on_delete=models.CASCADE, related_name='+'
)
caption = models.CharField(blank=True, max_length=64)
panels = [
ImageChooserPanel('image'),
FieldPanel('caption'),
]
home/templates/home/home_page.html
{% extends "base.html" %}
{% load static %}
{% load wagtailcore_tags wagtailimages_tags %}
{% block body_class %}template-homepage{% endblock %}
{% block content %}
{{ page.body|richtext }}
{% with page.thiswillfail|random as item %}
<div>
{% image item.image max-1000x1000 %}
<p>{{ item.caption }}</p>
</div>
{% endwith %}
{% endblock content %}
Even after adding some images in the Wagtail admin interface, I get the same error on the homepage: object of type 'DeferringRelatedManager' has no len()
I at least narrowed it down to the "with" statement in home_page.html. The wagtail image object is iterable in a for loop as in the start guide, but it would seem that it doesn't work with the random function. So, how can I get it to pick a random image object to show on the page?

Rather than getting a random image in the template, you could get the random image at the context for the template. This avoids the needs to apply the hack mentioned, and should make the code easier to follow for future.
Each Wagtail Page can provide a few method overrides to customise how the template renders. The simplest for this case would be get_cotext - see https://docs.wagtail.io/en/stable/topics/pages.html#customising-template-context
Django allows for querysets to be randomly ordered with order_by('?'), see https://docs.djangoproject.com/en/3.0/ref/models/querysets/#order-by
Code Example
home/models.py
# models.py
class HomePage(Page):
# ... fields & etc
def get_context(self, request):
context = super().get_context(request)
# Add extra variables and return the updated context
context['random_image'] = self.home_images.order_by('?').first()
return context
home/templates/home/home_page.html
{% extends "base.html" %}
{% load static %}
{% load wagtailcore_tags wagtailimages_tags %}
{% block body_class %}template-homepage{% endblock %}
{% block content %}
{{ page.body|richtext }}
{% image random_image.image max-1000x1000 %}
<p>{{ random_image.caption }}</p>
{% endblock content %}

Related

Django: ListView. Where can I declare variables that I want to have on template?

One of my tables in my app is called Gallery and I have the following class to list all of the objects on that table:
from django.views.generic import ListView
from galleries.models import Gallery
class GalleryList(ListView):
template_name = "path/to/template"
context_object_name = "object_list"
def queryset(self):
return Gallery.objects.order_by('-title')[:20]
And it does the job. On my template I do the following:
{% block gallery_list %}
<h1>Gallery List</h1>
<ul>
{% for gallery in object_list %}
<li><img src="{{ gallery.thumbnail.url }}" />{{ gallery.title }}</li>
{% endfor %}
</ul>
{% endblock %}
Everything works as expected. The thing here is that on my base.html template I have {% block title %} for the meta title tag, {% block description %} for my meta description tag in the header. And I want to be able to declare it somewhere and pass it to the view. To be clear, the variables title and description are strings (ex: title="List of all galleries on website").
On the view I want to do something like:
{% extends "base.html" %}
{% block title %}{{ title }}{% endblock %}
{% block description %}{{ description|default:title }}{% endblock %}
But, on the class GalleryList I don't know where to declare the variables title and description. I don't know if that's possible or proper for Django. I want to do what's right.
Also, as I have a costume template for listing all the galleries I could just do:
{% extends "base.html" %}
{% block title %}List of all galleries on website{% endblock %}
{% block description %}List of all galleries on website...{% endblock %}
But then again, I don't know if that's proper for a well coded Django app. I'm a beginner with Django and I would like to know what's the way to go about this. Hope my question is clear enough.
You can override the ListViews get_context_data method to add whatever additional context variables to you want to the context:
class GalleryList(ListView):
def get_context_data(self, **kwargs):
ctx = super(GalleryList, self).get_context_data(**kwargs)
ctx['title'] = 'My Title'
ctx['description'] = 'My Description'
return ctx
The other approach - of having a template that fills in this information - is also sound. Which is better really depends on how dynamic the data is. If the title/description is based on model data or some other factors, then it makes sense to set it in the view. If it is fixed for a particular template then it is probably cleaner to put in in a template that extends base.html.

TypeError at /careers/test/ jobpost_detail() got an unexpected keyword argument 'slug'

I installed the app careers mezanine and after creating a test position and turn the page to see the error TypeError at / careers / test /
jobpost_detail () got an unexpected keyword argument 'slug'. How do I fix this problem?
views
from calendar import month_name
from django.shortcuts import get_object_or_404
from collections import defaultdict
from django.contrib.contenttypes.models import ContentType
from django import VERSION
from careers.models import JobPost
from mezzanine.conf import settings
from mezzanine.generic.models import AssignedKeyword, Keyword
from mezzanine.utils.views import render, paginate
def jobpost_list(request, tag=None, year=None, month=None, template="careers/jobpost_list.html"):
"""
Display a list of job posts that are filtered by year, month.
"""
settings.use_editable()
templates = []
jobposts = JobPost.objects.published()
if tag is not None:
tag = get_object_or_404(Keyword, slug=tag)
jobposts = jobposts.filter(keywords__in=tag.assignments.all())
if year is not None:
jobposts = jobposts.filter(publish_date__year=year)
if month is not None:
jobposts = jobposts.filter(publish_date__month=month)
month = month_name[int(month)]
# We want to iterate keywords and categories for each blog post
# without triggering "num posts x 2" queries.
#
# For Django 1.3 we create dicts mapping blog post IDs to lists of
# categories and keywords, and assign these to attributes on each
# blog post. The Blog model then uses accessor methods to retrieve
# these attributes when assigned, which will fall back to the real
# related managers for Django 1.4 and higher, which will already
# have their data retrieved via prefetch_related.
jobposts = jobposts.select_related("user")
if VERSION >= (1, 4):
jobposts = jobposts.prefetch_related("keywords__keyword")
else:
if jobposts:
ids = ",".join([str(p.id) for p in jobposts])
keywords = defaultdict(list)
jobpost_type = ContentType.objects.get(app_label="careers", model="jobpost")
assigned = AssignedKeyword.objects.filter(jobpost__in=jobposts, content_type=jobpost_type).select_related("keyword")
for a in assigned:
keywords[a.object_pk].append(a.keyword)
for i, post in enumerate(jobposts):
setattr(jobposts[i], "_keywords", keywords[post.id])
jobposts = paginate(jobposts, request.GET.get("page", 1),
settings.CAREERS_PER_PAGE,
settings.MAX_PAGING_LINKS)
context = {"jobposts": jobposts, "year": year, "month": month, "tag": tag}
templates.append(template)
return render(request, templates, context)
def jobpost_detail(request, template="careers/jobpost_detail.html"):
""". Custom templates are checked for using the name
``careers/jobpost_detail_XXX.html`` where ``XXX`` is the job
posts's slug.
"""
jobposts = JobPost.objects.published()
jobpost = get_object_or_404(jobposts)
context = {"jobpost": jobpost, "editable_obj": jobpost}
templates = [u"careers/jobpost_detail_%s.html" %(slug), template]
return render(request, templates, context)
html
{% extends "careers/jobpost_list.html" %}
{% load mezzanine_tags keyword_tags i18n %}
{% block meta_title %}{{ jobpost.meta_title }}{% endblock %}
{% block meta_keywords %}{% metablock %}
{% keywords_for jobpost as tags %}
{% for tag in tags %}{% if not forloop.first %}, {% endif %}{{ tag }}{% endfor %}
{% endmetablock %}{% endblock %}
{% block meta_description %}{% metablock %}
{{ jobpost.description }}
{% endmetablock %}{% endblock %}
{% block title %}
{% editable jobpost.title %}{{ jobpost.title }}{% endeditable %}
{% endblock %}
{% block breadcrumb_menu %}
{{ block.super }}
<li class="active">{{ jobpost.title }}</li>
{% endblock %}
{% block main %}
<h6>
{% trans "Posted" %} {{ jobpost.publish_date|timesince }} {% trans "ago" %}.
</h6>
{% editable jobpost.content %}
{{ jobpost.content|richtext_filter|safe }}
{% endeditable %}
{% keywords_for jobpost as tags %}
{% if tags %}
{% spaceless %}
<ul class="unstyled tags">
<li>{% trans "Tags" %}:</li>
{% for tag in tags %}
<li>{{ tag }}</li>
{% endfor %}
</ul>
{% endspaceless %}
{% endif %}
{% set_short_url_for jobpost %}
<a class="btn small primary share-twitter" target="_blank" href="http://twitter.com/home?status={{ jobpost.short_url|urlencode }}%20{{ jobpost.title|urlencode }}">{% trans "Share on Twitter" %}</a>
<a class="btn small primary share-facebook" target="_blank" href="http://facebook.com/sharer.php?u={{ request.build_absolute_uri }}&t={{ jobpost.title|urlencode }}">{% trans "Share on Facebook" %}</a>
{% endblock %}
url
from django.conf.urls import patterns, url
# Job Post patterns.
urlpatterns = patterns("careers.views",
url("^tag/(?P<tag>.*)/$",
"jobpost_list",
name="jobpost_list_tag"),
url("^archive/(?P<year>\d{4})/(?P<month>\d{1,2})/$",
"jobpost_list",
name="jobpost_list_month"),
url("^archive/(?P<year>.*)/$",
"jobpost_list",
name="jobpost_list_year"),
url("^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>.*)/$",
"jobpost_detail",
name="jobpost_detail_date"),
url("^(?P<slug>.*)/$",
"jobpost_detail",
name="jobpost_detail"),
url("^$",
"jobpost_list",
name="jobpost_list"),
)
The error tells you exactly what is going on: your "jobpost_detail" URL the captures a slug parameter and passes it on to the view, but that view does not expect a slug, only the request and a template. Also, you are not doing anything in that view to get the actual post identified by a slug: you are always getting the first published post.
I suspect you want to do the following:
def jobpost_detail(request, slug, template="careers/jobpost_detail.html"):
jobposts = JobPost.objects.published()
jobpost = get_object_or_404(jobposts, slug=slug)

django inclusion tag not rendering

I'm working on an Inclusion Tag. In the super shell, the tag returns the appropiate data set nevertheles, I dont see the inclusion template rendered on the calling template. I can only guess the inclusion template is in the wrong location. As of this moment, the template is at MYPROJECT/templates which is the ONLY folder in TEMPLATE_DIRS. Please help me figure out what am I doing wrong here. TIA!
MYPROJECT/newsroom/templatetags/blog_extras.py -> http://pastebin.com/ssuLuVUq
from mezzanine.blog.models import BlogPost
from django import template
register = template.Library()
#register.inclusion_tag('featured_posts.html')
def featured_posts_list():
"""
Return a set of blog posts whose featured_post=True.
"""
blog_posts = BlogPost.objects.published().select_related("user")
blog_posts = blog_posts.filter(featured_post=True)
# import pdb; pdb.set_trace()
return {'featured_posts_list': blog_posts}
MYPROJECT/templates/featured_posts.html -> http://pastebin.com/svyveqq3
{% load blog_tags keyword_tags i18n future %}
Meant to be the the infamous "Featured Posts" Section!
{{ featured_posts_list.count }}
<ul>
{% for featured_post in featured_posts_list %}
<li> {{ featured_post.title }} </li>
{% endfor %}
</ul>
MYPROJECT/settings.py -> pastebin.com/Ed53qp5z
MYPROJECT/templates/blog/blog_post_list.html -> pastebin.com/tJedXjnT
As #Victor Castillo Torres said, you need to change the name of the tag you're loading, which will fix that aspect of your template tag. However, even though they are in different namespaces, I would still change the name of the context variable your tag returns just for sanity:
#register.inclusion_tag('featured_posts.html')
def featured_posts_list():
blog_posts = BlogPost.objects.published().filter(
featured_post=True).select_related("user")
return {'blog_posts': blog_posts}
Then in your template:
{{ blog_posts.count }}
<ul>
{% for blog_post in blog_posts %}
<li>{{ blog_post.title }} </li>
{% endfor %}
</ul>
And finally, in your main template:
{% load blog_extras keyword_tags i18n_future %}
...
{% featured_posts_list %}

How to pass one-to-many relationship to context on objects.all() lookup as iterable

I'm having trouble trying to wrap my head around this. many-to-one relationships are well documented, but I can't find an example on how to pass all of the relationships of a model.objects.all() lookup to context.
I'm trying to do something like
models.py
from django.db import models
class Image(models.Model):
image_file = models.ImageField()
imageset = models.ForeignKey(ImageSet)
class ImageSet(models.Model):
title = models.CharField(max_length)
views.py
from django.shortcuts import render
from models import Image, ImageSet
def images(request):
imagesets = ImageSet.objects.all()
return render(request, 'template.html', {'imagesets': imagesets})
template.html
{% for imageset in imagesets %}
{{ imageset.title }}
{% for image in imageset.images %}
<img src="{{image.image_file.url}}" alt="">
{% endfor %}
{% endfor %}
I've tried imagesets = ImageSet.objects.all().prefetch_related() but it only seems to work for ManyToMany relationships.
Given an instance of the ImageSet model, you can access the related images with...
images = my_imageset.image_set.all()
...so you can just change the template to...
{% for imageset in imagesets %}
{{ imageset.title }}
{% for image in imageset.image_set.all %}
<img src="{{image.image_file.url}}" alt="">
{% endfor %}
{% endfor %}
See the Django documentation on Related objects for more information.
views.py will be like this:-
from django.shortcuts import render
from models import Image, ImageSet
def images(request):
t=get_template("template.html")
imagesets = ImageSet.objects.all()
image = Image.objects.all()
html=t.render(Context({'imagesets':imagesets,'image':image}))
return HttpResponse(html)
In template.html:
{% for image in imageset.images %} line will not work as imageset.image does not
exist because Imageset model having only one field title so you cat't access that.
if you want to access image field of Image model then from views.py you have to send
that object also.
and <img src="{{image.url}}" alt=""> will not work. where is your url field??
---------thanks-------

Custom django-admin templates

I've got a model, and my instance called "show_user_image":
class user_image(models.Model):
title = models.CharField(max_length=50)
img = models.imageField(upload_to='/home/blabla')
def show_user_image(self):
return u'<img src="%s" />' % self.img.url
show_user_image.short_description = 'User image'
image_img.allow_tags = True
off course i can use it at my admin list:
list_display = ('title', 'show_user_image')
And my question is: how to use this instance in the edit form?
Something like here:
http://new-media.djangobook.com/content/en/1.0/chapter17/book_extra.png
{% extends "admin/change_form.html" %}
{% block form_top %}
<p>Insert meaningful help message here...</p>
{% endblock %}
but i want:
{% extends "admin/change_form.html" %}
{% block form_top %}
{{ MY-INSTANCE-HERE }}
{% endblock %}
I just need to image display above the form.
Thanks!
John.
The form is admin template is available via adminform.form variable. Your field is named img, so it will be like this (untested):
{% block form_top %}
<img src="{{ adminform.form.img.value }}"/>
{% endblock %}
BTW. Class names in python should use CapitalizedWordsNamingConvention, according to official style guide. You should name the model UserImage instead of user_image.
BTW2: show_user_image is a method, not an instance.

Categories