I was faced with the fact that I wanted to post 2 paragraph-long summaries on one of my sites, and this is what I did (you could of course cut it down earlier, but I'd say this belongs to what is called "template logic")
Use like so:
{% load myExtraModule %}
{{ blogpost.content|paragraphs:"2" }}
The lines filter works the exact same way, and you might want to improve on these a bit, I don't maintain them as I don't use them anymore.
This code is derived from the slugify JS function used in django's admin interface. It will create django-compatible slugs for you. Sometimes I do batch imports and need my items to have slugs, I give this script the item's title and get a slug back.
Simple
Convert plain text to html. For example:
text="""aabhttp://www.example.com http://www.example.com
http://www.example.com <<< [<aaaa></aaaa>]
"""
print plaintext2html(text)
It can convert url text to html href. And it also can convert space to . So if you paste python code, the indent will not lost at all. Default it'll convert \t to 4 spaces.
Can be used for create a json format response data. Just like:
{response:'ok', next:'nexturl', message:'response message', data:'returned data'}
for success.
{response:'fail', next:'nexturl', message:'response message', error:'error messages'}
for failure.
And there are some dump function:
json - dump a python variable into json format string
json_response - dump a python variable into json format string, and then use it create a HttpResponse object.
An example on how we changed our localization middleware to use www-en.<domain> instead of it being hidden in the cookie.
This also changes zh-cn to cn, and zh-tw to tw in the URLs.
This is only a base snippet and you will most likely need to modify it to fit your needs.
This utility is useful when you want to safely retrieve a single object from the database without having to wrap get() in a try/except block every time.
It also supports query optimization via select_related and prefetch_related, making it ideal for performance-conscious applications.
If you have multiple items in a list and want them to be displayed as human readable list of items, this will add the proper punctuation to generate the text. You'll need to provide a conjugation to the end of the list like "or" or "and"; it defaults to "or".
Intended use:
`{% for item in items %}{{item}}{% list_punctuation forloop "and" %}{% endfor %}`
* If items was `['a']`; the template would return `a`.
* If items was `['a', 'b']`; the template would return `a and b`.
* If items was `['a', 'b', 'c']`; the template would return `a, b, and c`.
Sometimes a plain-text help-text isn't sufficient, and it's handy to be able to add links to pages, documentation or external websites.
This javascript snippet can be added to your page, in combination with adding a class to your help text in your template. This assumes you're using jQuery on your website.
Field template snippet:
```
{% if field.help_text %}<p class="help-text">{{ field.help_text }}</p>{% endif %}
```
On document ready, this will convert the markdown-style links into anchor tags, allowing you to have richer help text for your users
Add fields and extend Django's built-in `Group` model using a `OneToOneField` (i.e. a profile model). In this example, we add a `UUIDField`. Whenever a new group is created, we automatically (via signals) create a corresponding `Role` record referencing the newly created group. Whenever a Group is deleted, the corresponding Role is deleted as well.
Most modern browsers support the new `<input type="date">`, which allows inputting date using a browser-native date picker with built-in validation. This form widget utilizes this feature by setting the input type to "date" and by changing the value formatting as it should be in the ISO format.
See more about `<input type="date">`: <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date>
Make `cache_page` optional, depending on the result of a callable. Uncomment the added lines if you want to make sure that the consumers don't know the page is cached – that means more hits on your end, but also a guarantee that they will always get the newest data asap.
#### Allows to fetch a row or array of rows of data, linked to parent object, in a single query. Data is fetched as JSON and is not serialized into Django objects.
##### Example:
from django.db import Models
class Book(models.Model):
authors = models.ManyToMany('Author', through='BookToAuthor', blank=True)
title = models.CharField(max_length=512, default='')
class Author(models.Model):
name = models.CharField(max_length=512, default='')
class BookToAuthor(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
##### Download author with all his/her books in a single query
from django.db.models import OuterRef
books_by_author_subquery = Book.objects.filter(
id__in=BookToAuthor.objects.filter(author_id=OuterRef(OuterRef('id')))
).values('title')
author = Author.objects\
.annotate(books=SubqueryJsonAgg(books_by_author_subquery))\
.get(id=1)
Here's how to find the 10 closest locations to a point for a model that has latitude and longitude columns, if you're not using GeoDjango.
This runs a brute force distance calculation against every row, so it should only be used on smaller tables - probably less than 100,000 rows.
For larger tables you should use GeoDjango instead.
See also [my TIL](https://til.simonwillison.net/postgresql/closest-locations-to-a-point) about this.
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.