Login

All snippets

Snippet List

Query lookups using operators

This class emulates query lookups to behave as numeric operators. Inspired by SQLAlchemy. User.objects.filter( X('username') == 'diverman' ) User.objects.filter( X('username') != 'diverman' ) User.objects.filter( X('pk') > 10 ) User.objects.filter( X('pk') >= 10 ) User.objects.filter( X('pk') < 10 ) User.objects.filter( X('pk') <= 10 ) User.objects.filter( X('username') % 'iverma' ) User.objects.filter( X('username') << 'diver' ) User.objects.filter( X('username') >> 'man' ) User.objects.filter( X('pk') | (1, 2, 3) )

  • q
  • query
  • lookup
  • operator
Read More

Reset / Send account details email

I needed to create a feature for administrators to create accounts and email the *new account was created* email using a button. Remember to change the default template and subject to match your needs. The code is directly taken from `django.contrib.auth.forms.PasswordResetForm.save()`. Notice that the function raises `ValueError` if the user is missing an email address.

  • users
  • reset-password
Read More

adding fields to User model

This code adds new field to Django user model. It must be executed early as much as possible, so put this code to __init__.py of some application.

  • fields
  • model
  • user
  • auth
  • field
Read More

Django csrf_token Template Tag Fix

If you currently use `{% csrf_token %}`, you will notice it prints a hidden div, and an xHTML input tag. What if you don't want that hidden div, and/or you want your page to validate with HTML and not xHTML. This snippet returns only the csrf token itself, and none of the related HTML code. You can use it like this. `<input type="hidden" name="csrfmiddlewaretoken" value="{% with csrf_token as csrf_token_clean %}{{ csrf_token_clean }}{% endwith %}" >`

  • csrf_token
  • csrf_token_clean
Read More

Filter to generate QR codes

You can convert any string to a QR code image as easy as use a simple filter, thanks to google charts api. Common use: <img src="{{object.attribute_to_encode|qr:"120x130"}}" /> This will create a 120(width) x 130(heiht) image with the value of the attribute_to_encode encoded in a QR coded image.

  • filter
  • templatetag
  • templatefilter
  • barcode
  • qr
Read More

Use both NTLM and Anonymous authentication with IIS

Point '^accounts/login/$' or whatever your custom login path is to the 'negotiate_ntlm' view. This allows you to keep anonymous authentication enabled on IIS and easily lock down just the parts of the site you need to (e.g. [admin](http://djangosnippets.org/snippets/2127/)).

  • admin
  • authentication
  • anonymous
  • iis
  • ntlm
Read More

Interactive Profiling Middleware

Based on [Extended Profiling Middleware](http://djangosnippets.org/snippets/605/), this version allows interactive sorting of functions and inspection of SQL queries.

  • middleware
  • profile
  • hotshot
Read More

Database cleanup

***About*** I tried to dump data from my database (manage.py dumpdata) and I couldn't do it because of error: User matching query does not exists I found out that my database was filled with garbage: entries those foreigners were deleted. My table's engine is MyISAM so it allows for these lost entries to exist. I had to cleanup my database before I do datadump, so I've written a script which worked fine for me. ***Usage*** Place this script in same directory with your settings.py and run it: `python db_cleanup.py` ***Disclaimer*** Backup your data :)

  • dumpdata
Read More

"Autoconnect" model decorator, easy pre_save and post_save signal connection

This method allows you to define pre_save and post_save signal connections for your decorators in a little more clean way. Instead of calling `pre_save.connect(some_func, sender=MyModel)`, or perhaps `pre_save.connect(MyModel.some_static_func, sender=MyModel)`, you can simply define the pre_save method right on your model. The @autoconnect decorator will look for pre_save and post_save methods, and will convert them to static methods, with "self" being the instance of the model.

  • pre_save
  • post_save
  • signal-connect
Read More

CurrentSessionIDMiddleware

The middleware assigns a unique identifier for session. The session id doesn't depend of session or whatever else. It only need cookies to be turned on. The session id is reassigned after client close a browser. Identifier of the session could be read from request: request.current_session_id. You can setup name of the cookie in yours settings module (FLASH_SESSION_COOKIE_NAME). request.current_session_id is lazy. It means the ID will be assigned and cookie will be returned to client after first usage.

  • middleware
  • session
Read More

Arbitrary auto-generated primary keys

Auto-incremented primary keys are the default in Django and they are supported natively in most databases but for anything more complex things are less trivial. DB sequences are not standard, may not be available and even if they are, they are typically limited to simple integer sequence generators. This snippet bypasses the problem by allowing arbitrary auto-generated keys in Python. The implementation needs to determine whether an IntegrityError was raised because of a duplicate primary key. Unfortunately this information is not readily available, it can be found only by sniffing the DB-specific error code and string. The current version works for MySQL (5.1 at least); comments about how to determine this in other databases will be incorporated in the snippet.

  • mysql
  • sequence
  • uuid
  • auto decrement
  • auto increment
  • primary key
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

3109 snippets posted so far.