Login

Top-rated snippets

Snippet List

Line & paragraph chopping

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.

  • chop
  • cut
  • line
  • paragraph
  • block
Read More

slugify js -> python

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

  • slugs
Read More

convert plain text to html

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 &nbsp;. So if you paste python code, the indent will not lost at all. Default it'll convert \t to 4 spaces.

  • text
Read More

ajax protocol for data

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.

  • ajax
  • serialize
Read More

Localized URLs (www-en)

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.

  • internationalization
  • middleware
  • il8n
  • urls
Read More

get_object_or_none

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.

  • orm
  • queryset
  • utils
  • select_related
  • get_or_none
  • prefetch_related
Read More

Template tag - list punctuation for a list of items

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`.

Read More

Help text hyperlinks

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

  • help
  • link
  • documentation
  • docs
  • href
  • help_text
Read More

Add custom fields to the built-in Group model

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.

  • model
  • group
  • uuid
  • signals
Read More

Browser-native date input field

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>

  • forms
  • datefield
  • widget
  • input
Read More

A wrapper around cache_page making it optional

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.

  • cache
  • caching
  • cache_page
Read More

PostgreSQL JSON subqueries

#### 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)

  • json
  • postgres
  • postgresql
  • subquery
Read More

Closest ORM models to a latitude/longitude point

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.

  • orm
  • gis
  • latitude
  • longitude
  • location
Read More

3110 snippets posted so far.