using django-easy_thumbnails from view - python

easy_thumbnails is a big help when making models or views for thumbnails.
I am using the templatetag (via template, not via model) and easy_thumbnails creates sucessfully the thumbnail files.
what happen when I want to use easy_thumbnails via view, not model o templatetag (the rendering of the images is via ajax, and django will not parse the templatetag...) for example imagine displaying infinite image thumbnails for this plugin http://sorgalla.com/projects/jcarousel/examples/dynamic_ajax_php.html . any lights? thanks!.

I'm not sure what you're asking about, but README file from easy_thumbnails should cover your use case.
And if for some reason it doesn't and you want to use {% thumbnail %} tag directly in a view, then you can always render_to_string a template that contains just: {% thumbnail %} tag, although this looks to me like a hack.

Related

Creating objects/functions within Jinja to better re-use code

I'm currently working on a practice blog site to learn more about web development and I am using Flask.
On my site, people can create blog posts and view the posts of others. Obviously, I want to make my code as re-usable as possible. So right now, depending on the page, I am grabbing some number of blog posts in my routes.py, and then passing them into a number of different pages (e.g. home page, profile page, search page).
Each of these pages has its own template since they all look different. However, the code for displaying the blog posts is the same in all of the sites, even though the blog posts themselves may differ. Is there any way in Jinja to create an object or function (e.g. render_as_blog_posts()) to which I could pass in the blog posts to and run in the template? For example:
routes.py
def profile():
blog_posts=profile_blog_posts
return render_template("profile.html",posts=blog_posts)
def search():
blog_posts=search_blog_posts
return render_template("search.html",posts=blog_posts)
profile.html:
<html>
<title>Profile</title>
{{ render_as_blog_posts(blog_posts) }}
</html>
search.html:
<html>
<title>Search</title>
{{ render_as_blog_posts(blog_posts) }}
</html>
I suppose, you're looking for the 'template inheritance' feature of Jinja2: https://jinja.palletsprojects.com/en/2.10.x/templates/#template-inheritance
Basically, you can achieve what you want in the different ways:
Template extension: https://jinja.palletsprojects.com/en/2.10.x/templates/#base-template
In this case you can define base template with common layout, common set of macroses and define special blocks in this template as a points of customization. Then, you can extend this template and fill blocks in the way specific for derived template (see samples by the provided link)
Templates import: https://jinja.palletsprojects.com/en/2.10.x/templates/#import
More specific feature which looks like exactly the same python's one. You can define special template which contains set of macros and then import this template into yours profile.html or search.html:
{% import 'commmon_functions.html' as common %}
Then you can refer functions from this file as a part of common namespace:
{{ common.render_as_blog_posts(blog_posts) }}

How to add custom HTML elements and images to a blog in Django?

I am trying to create a blog in Django. Most of the tutorials and examples available shows just retrieving some content from the database and displaying it dynamically on the predefined HTML structure.
After looking at some solution I found something called flatpages in Django which provide the facility to write HTML. But its recommended to use it for About Us and Contact Us kind of pages. Should I use this?
I want to do it as I can write my own HTML data for each blog and add some images so that the structure of HTML should not be similar in each blog.
For example, In the case of WordPress, it allows the user to completely write each part of the blog except the heading part and the structure of HTML is not constant always.
I want such functionality. Please help.
What you are looking for is to upload images and embed them as html in your content field. This can be done using a WYSIWYG Editor such as CKEditor. In CK you can write your text, format it and upload files. You could use django-ckeditor to do the heavy lifting for you: https://github.com/django-ckeditor/django-ckeditor
In your template you then have to render your content with safe filter so that the content will be rendered as html:
{{ post.content |safe }}
Have you tried using the static directory? It stores the static content like CSS, Image etc. Create the Static and join it with the BASE_DIR in settings.py file. A full explanation is given here. https://docs.djangoproject.com/en/2.2/howto/static-files/
There are a bunch of packages that already do this. You can refer to Django Packages and pick the one that suits your needs the best.
Mezzanine is one of the most common ones. I personally have not used it.
I've seen Django-cms being used at one of my previous jobs. It was quite powerful, but I personally did not like it a lot.
If you'd like to create your own CMS, you could go for a very basic structure like
class BlogImage(models.Model):
image = models.ImageField()
alt_text = models.CharField(max_length=128)
class BlogPost(models.Model):
title = models.CharField(max_length=512)
content = models.TextField() # be sure to validate that this does not contain bad code
tags = models.ManyToMany(Tag)
Give the users a WYSIWYG editor like CKEditor. If users want to include images the just need to use the URL to it. If they want to upload, give them a modal or some different page to upload the image and copy the link to the image into the HTML markup

How do I display static images that are in content variable in django?

I have a django site where a portion is basically a CMS. There are large content blocks (like the content of a post) held in a database and within those I need to display images that are in my static files. The content within the content block could be anything just like a regular blog post so there may be images scattered within it.
I am displaying the content in a template using the following
{{content | safe}}
I can display the images if I put the full url but that is not optimal as it doesn't use the advantages of the Django static files system. How do I go about displaying these since I can't use the {% static %} tag for the images that are within the content?
This seems like a place to use a custom filter. There are probably a lot of different ways to do it, but one could look like this:
from django import template
from my_project import settings
register = template.Library()
#register.filter
def img_link(content):
return content.replace('src=','src='+settings.STATIC_URL')
That's assuming you already have the code in your content look something like -- you can adjust the filter to meet however your images are actually written in the content. Because this is relying on the STATIC_URL from your settings, it will adjust whenever the URL is changed, exactly as {% static %} would.
of course, filters can be chained, so you could just write {{content|safe|img_link}} to activate the filter.

Django Rendering Template Included in a Template

Basically I have a base template, and the base template is including another template, let's say, latest update. So the structure is like this:
-base.html
|---------latest_update.html
So, I know how to include a simple template, like the template without any data processing (doesn't require interaction with any application view.py). However, how could I attach the included template into a django application view.py so that I could at least show updated data periodically?
I am not exactly sure terms for this, feel free to change the title.
Edit: This question is a bit cloudy, as I don't know how to put the terminology correctly. So, I have this included template. Every page will have it. So, from my limited knowledge, that means I have to render it manually for every page that hits view.py. Is there any easier way of doing this?
You can use Django templatetags. Define a file named latest_update_tags under your Django app templatetags directory and write code like this to define a latest_update templatetags:
from django import template
from app.models import UpdateObject
register = template.Library()
#register.inclusion_tag("latest_update.html")
def latest_update():
update_objects = UpdateObject.all().[:10]
return {"update_objects": update_objects}
And then in your base.html use it like this:
{% load latest_update_tags %}
......
{% latest_update %}

Rendering JSON objects using a Django template after an Ajax call

I've been trying to understand what's the optimal way to do Ajax in Django. By reading stuff here and there I gathered that the common process is:
formulate your Ajax call using some JavaScript library (e.g., jQuery), set up a URL pattern in Django that catches the call and passes it to a view function
in the Python view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or simplejson)
define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.
Now, what I still don't get is how are Django templates related to all of this? Apparently, we're not making use of the power of templates at all.
Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...
The only resource I found that goes in this direction is this snippet (769) but I haven't tried it yet.
Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.
Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?
Many thanks!
UPDATE: please use snippet 942 because it is an enhanced version of the one above! I found that the inheritance support works much better this way..
Hey thanks vikingosegundo!
I like using decorators too :-).
But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead the snippet n. 942 cause it's an improved version of the original one. Here's how it works:
Imagine you have a template (e.g., 'subtemplate.html') of whatever size that contains a useful block you can reuse:
........
<div id="results">
{% block results %}
{% for el in items %}
<li>{{el|capfirst}}</li>
{% endfor %}
{% endblock %}
</div><br />
........
By importing in your view file the snippet above you can easily reference to any block in your templates. A cool feature is that the inheritance relations among templates are taken into consideration, so if you reference to a block that includes another block and so on, everything should work just fine. So, the ajax-view looks like this:
from django.template import loader
# downloaded from djangosnippets.com[942]
from my_project.snippets.template import render_block_to_string
def ajax_view(request):
# some random context
context = Context({'items': range(100)})
# passing the template_name + block_name + context
return_str = render_block_to_string('standard/subtemplate.html', 'results', context)
return HttpResponse(return_str)
Here is how I use the same template for traditional rendering and Ajax-response rendering.
Template:
<div id="sortable">
{% include "admin/app/model/subtemplate.html" %}
</div>
Included template (aka: subtemplate):
<div id="results_listing">
{% if results %}
{% for c in results %}
.....
{% endfor %}
{% else %}
The Ajax-view:
#login_required
#render_to('admin/app/model/subtemplate.html')#annoying-decorator
def ajax_view(request):
.....
return {
"results":Model.objects.all(),
}
Of course you can use render_to_response. But I like those annoying decorators :D
There's no reason you can't return a rendered bit of HTML using Ajax, and insert that into the existing page at the point you want. Obviously you can use Django's templates to render this HTML, if you want.
When you are doing Ajax I don't think you have any use for templates.
Template is there so that you can generate dynamic HTML on the server side easily and hence it provides few programming hooks inside HTML.
In case of Ajax you are passing JSON data and you can format it as you want in Python.
and HTML/document elements will be generated on client side using the JSON by some JavaScript library e.g. jQuery on client side.
Maybe if you have a very specific case of replacing some inner HTML from server side HTML then maybe you can use templates but in that case why you would need JSON?
You can just query the HTML page via Ajax and change inner or outer or whatever HTML.
Templates are for the purpose of presentation. Responding with data in format X (JSON, JSONP, XML, YAML, *ml, etc.) is not presentation, so you don't need templates. Just serialize your data into format X and return it in an HttpResponse.
While templates are indeed just for presentation purposes, it shouldn't matter if you are doing it on the serverside or client side. It all comes down to separating the control logic that is performing an action, from the view logic that is just responsible for creating the markup. If your javascript control logic is having to handle how you are rendering or displaying the HTML, then you might be doing it wrong, but if you isolate that rendering logic to another object or function, and just passing it the data necessary for the render, then you should be fine; it mirrors how we separate our controllers, models and views on the server side.
Take a look at the github project: http://github.com/comolongo/Yz-Javascript-Django-Template-Compiler
It compiles django templates into optimized javascript functions that will generate your presentation html with data that you pass it. The compiled functions are in pure javascript, so there are no dependencies on other libraries. Since the templates are compiled instead of being parsed at runtime, the strings and variables are all already placed into javascript strings that just need to be concatenated, so you get a huge speed increase compared to techniques that require you to do dom manipulation or script parsing to get the final presentation. Right now only the basic tags and filters are there, but should be enough for most things, and more tags will be added as people start making requests for them or start contributing to the project.
You can use jquery.load() or similar, generating the HTML on the server and loading it into the DOM with JavaScript. I think someone has called this AJAH.
Unfortunately, Django templates are designed to be executed server side only. There is at least one project to render Django templates using Javascript, but I haven't used it and so I don't know how fast, well supported or up to date it is. Other than this, you have to either use the Django templates on the server or generate dynamic elements on the client without using templates.

Categories