I have a ModelForm which includes m2m field to images. User can upload images and crop them with my cool jquery cropper, then areas are saved as images and their IDs and thumbnail URLs are passed back to page and included as thumbnails with hidden inputs. I have no problem while form have no errors, and when it does, i can not just simply display thumbnails — all I have is IDs, and form has no objects to iterate cause instance was not saved, and as it was not save it has no id and as it has no id it can not have m2m relations. So i wrote templatetag which returns queryset based on ids. It works like that:
<ul id="lot-images" class="thumb-uploaders">
{% if form.errors %}
{% load load_form_objects %}
{% load_form_objects lot_form.images as images %}
{% for image in images %}
{% if image %}
<li>
<input type="hidden" name="images" value="{{image.id}}"/>
<div class="image">
<div class="mask"></div>
<img src="{{ image.get_thumbnail_url }}" alt=""/>
<a href="#" class="delete">Удалить</a>
</div>
</li>
{% else %}
<li><a class="upload-medium"></a></li>
{% endif %}
{% endfor %}
{% else %}
<li><a class="upload-medium"></a></li>
<li><a class="upload-medium"></a></li>
<li><a class="upload-medium"></a></li>
<li><a class="upload-medium"></a></li>
<li><a class="upload-medium"></a></li>
{% endif %}
</ul>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | from django.template import Library, Node, Variable
register = Library()
class LoadFormObjectsNode( Node ):
def __init__( self, form_objects, var_name ):
self.var_name = var_name
form, self.field = form_objects.split('.')
self.form = Variable(form)
def render( self, context ):
form = self.form.resolve( context )
object_ids = form.data.getlist(self.field)
objects = form.fields[self.field].queryset
objects = objects.filter(pk__in=object_ids)
context[self.var_name] = objects
return ''
@register.tag
def load_form_objects( parser, token ):
"""Parse template tag: {% load_form_objects form.objects as objects %}"""
bits = token.contents.split()
if len( bits ) != 4:
raise TemplateSyntaxError, "load_form_objects form.objects as objects"
if bits[2] != 'as':
raise TemplateSyntaxError, "third argument to the load_form_objects tag must be 'as'"
return LoadFormObjectsNode( bits[1], bits[3] )
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.