Login

Tag "django"

Snippet List

Export Django data to datestamped tarball -- choose individual models for handy packaging and archiving

Just like it says -- set it up and run. Use it for server migrations, for project handoffs, in cron jobs, you name it. I have never had problems exporting models to individual fixtures in this way, and only one bout of trouble re-importing them (and that was, like, an impossible-triangle of OneToOneField dependencies anyway, and they were going from a sqlite file to a postgres schema that totally had inappropriate nullable columns in it). I find that the json files named for what they contain is helpful when and if manage.py does freak out during an import, as the output from `loaddata` command is so opaque it's autistic, basically. A trivial refactoring effort could make it into a management command -- it already makes use of the builtin `dumpdata` command class internally. However I did not feel like overthinking it enough to set it up in a repository (doubtlessly padded with unrelated 'utilities' and explanatory .rst files) and then writing a blog post to sell it to you. That is why you are reading this code here, instead of on GitHub. Don't get me wrong, GitHub is awesome, and like a consummate host... but not the way I love me some quick and dirty snippet code, these days. Whatever, you say lazy, I say productively relaxed, potato/potahto. Erm. In any case please do enjoy this model fixture-exporter. Yes.

  • django
  • python
  • json
  • export
  • data
  • script
  • command
  • archive
  • django1.1
  • backup
  • datestamp
  • tar
  • tarball
Read More

Improved many-page pagination

This one was adapted from [Page numbers with ... like in Digg](http://djangosnippets.org/snippets/1441/). See that one for more reference. Digg-like page numbering using inclusion tag. Usage in template: `{% load pagination %} {% pagination yourpage %}` Inclusion template pagination.html: {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}"><img src="{{ MEDIA_URL }}images/page/cyclenav_l.png" alt="Previous page" /></a> {% endif %} {% for pnum in begin %} <a href="?page={{ pnum }}"{% if page.number == pnum %} class="active"{% endif %}>{{ pnum }}</a> {% endfor %} {% if middle %} <strong>...</strong> {% for pnum in middle %} <a href="?page={{ pnum }}"{% if page.number == pnum %} class="active"{% endif %}>{{ pnum }}</a> {% endfor %} {% endif %} {% if end %} <strong>...</strong> {% for pnum in end %} <a href="?page={{ pnum }}"{% if page.number == pnum %} class="active"{% endif %}>{{ pnum }}</a> {% endfor %} {% endif %} {% if page.has_next %} <a href="?page={{ page.next_page_number }}"><img src="{{ MEDIA_URL }}images/page/cyclenav_l.png" alt="Previous page" /></a> {% endif %}` Produces: previous_img 1 2 ... 4 5 6 7 8 9 10 11 12 ... 17 18 next_img Or: 1 2 3 4 5 6 7 8 ... 17 18 next_img Or: previous_img 1 2 ... 10 11 12 13 14 15 16 17 18 next_img

  • tag
  • django
  • templatetag
  • pagination
  • digg
  • pages
Read More

mkrange - create a range() inside a template - variable/filter support for range values

Ok, I just took [wolever](http://djangosnippets.org/users/wolever/)'s snippet at [http://djangosnippets.org/snippets/1926/](http://djangosnippets.org/snippets/1926/) and added template variable/filter support for range values. For instance, you could write something like this: `{% mkrange 1 tool_page.paginator.num_pages|add:"1" as page_range %}` I'm just learning python and django, so any advice would be appreciated.

  • django
  • python
  • custom tag
Read More

Template Tag for Random Selection of Any Line

These are template tags meant to support the construction of text in a random or seeded random (reproducible) way. Two tags are provided: `seed_randomization` and `any`. Only seed the randomization if you wish to have the options generated the same way each time. Only necessary once per request, if done early enough in the rendering process. Example without seeding: <p> {% any %} One day Once upon a time In a galaxy far, far away {% endany %} a young foolish {% any %}programmer|lawyer|Jedi{% endany %} {% any %} set out began his quest ran screaming {% endany %} to pay his stupid tax. </p> # Possible outcomes: <p>In a galaxy far, far away a young foolish lawyer set out to pay his stupid tax.</p> <p>One day a young foolish programmer ran screaming to pay his stupid tax.</p> Be sure to read the documentation in the code.

  • tag
  • django
  • random
Read More

Testserver: --noinput option, sending a signal

Makes manage.py testserver accept a `--noinput` argument to delete test database without asking if it already exists; makes it emit `django.core.management.commands.testserver.testserver_setup` signal after fixtures are loaded and before server itself is started to allow custom postprocessing.

  • django
  • patch
  • testserver
Read More

Django-admin autoregister -- automatic model registration

Automatically register models for the Django-admin. This snippet aids in the process of keeping your admin.py up-to-date with the models in your apps, have all models automatically added to the admin and reflect any future changes without updating the file. [zweckdev.com](http://zweckdev.com/)

  • django
  • models
  • admin
  • model
  • django-admin
  • autoregister
  • auto-register
Read More

Generating aggregate data across generic relations

http://github.com/coleifer/django-generic-aggregation http://charlesleifer.com/blog/generating-aggregate-data-across-generic-relations/ Generate and calculate aggregations across generic foreign keys. >>> from misc import generic_annotate, generic_aggregate >>> from blog.models import Entry >>> from tagging.models import TaggedItem >>> from django.db.models import Count >>> qs = generic_annotate(Entry.objects.all(), TaggedItem.object, 'id', Count) >>> qs[0].score 5L >>> qs[1].score 4L >>> qs[1].tags u'databases django many-to-many python' >>> generic_aggregate(Entry.objects.all(), TaggedItem.object, 'id', Count) 106L # total number of times entries were tagged

  • django
  • gfk
  • aggregation
Read More

ISBN model field: displays 10- and 13-digit variants and external links

Requires [PyISBN](http://pypi.python.org/pypi/pyisbn/0.5.2). Use like so: class Book(models.Model): title = models.TextField() isbn = ISBNField() ... the link in the widget can be changed to amazon, borders, you name it. If the DB version is a 13-digit ISBN, the display box contains the 10-digit, labeled; and vice-versa.

  • django
  • model
  • python
  • widget
  • modelfield
  • isbn
  • books
Read More

Email queue in DB

This is what I use to send simple status emails from my sites. Instead of a django.core.mail.send_mail call, which can take an irrritatingly, nondeterministically long time to return (regardless of error state), you can stow the emails in the database and rely on a separate interpreter process send them off (using a per-minute cron job or what have you). You then also have a record of everything you've sent via email from your code without having to configure your outbound SMTP server to store them or anything like that. Usage notes are in the docstring; share and enjoy.

  • django
  • python
  • email
  • mail
  • database
  • queue
  • asynchronous
Read More

RML2PDF with Django

This is a django view that can return a PDF made using rml2pdf from reportlab. This RML is written with django templating system, to view the rml code and download a fully working version visit [reportlab](https://www.reportlab.com/software/documentation/sample-projects/rml-with-django/)

  • django
  • pdf
  • rml
  • reportlab
Read More

SerializedObjectField

Model field that stores serialized value of model class instance and returns deserialized model instance. Example usage: from django.db import models import SerializedObjectField class A(models.Model): object = SerializedObjectField(serialize_format='json') class B(models.Model): field = models.CharField(max_length=10) b = B(field='test') b.save() a = A() a.object = b a.save() a = A.object.get(pk=1) a.object <B: B object> a.object.__dict__ {'field': 'test', 'id': 1}

  • django
  • models
  • fields
  • json
Read More

Context processor for django admin app_list

I never found a good snippet or tutorial to get the app_list (in django.admin) on other pages except the index page. So i started asking on irc j00bar has given me a very nice answer, but first i didn't know what to do with it till now. Anyways this snippet is very handy for the people who wants this but don't know how to get it. This is special made for the django version 1.1 Installation is quite easy, it is a context processor, so download this file put anywhere in your project, i got it in a app called cms_theme (theme and template related stuff.) and put the location in your settings.py file, example: `TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.request', '****cms.cms_themes.context_processors.theme', '****cms.cms_themes.context_processors.applist', )` The '****' stuff is nothing, i replaced my company name with it. Of course you may put the context processor anywhere else, that is your choice. Good luck! Alexander

  • django
  • models
  • admin
  • python
  • applications
  • app_list
  • app-models
Read More

Template Tag to protect the E-mail address

This is a Django Template Tag to protect the E-mail address you publish on your website against bots or spiders that index or harvest E-mail. It uses a substitution cipher with a different key for every page load. It basically produce a equivalent Javascript code for an email address. This code when executed by browser make it mailto link. **Usage** `{% encrypt_email user.email %}` **More Info ** [Template Tag to protect the E-mail address](http://www.nitinh.com/2010/02/django-template-tag-to-protect-the-e-mail-address/)

  • template
  • django
  • javascript
  • email
  • template-tag
  • obfuscate
  • bots
  • spider
Read More

213 snippets posted so far.