Example model:
class MyModel(models.Model):
file = RemovableFileField(upload_to='files', \
null=True, blank=True)
image = RemovableImageField(upload_to='images', \
null=True, blank=True)
A delete checkbox will be automatically rendered when editing such a model using form_for_instance.
[UPDATED version which works with ModelForms](http://www.djangosnippets.org/snippets/636/)
**Explanation:**
I think this shortcut can be util for who uses JSON many times and does not want to write same code everytime.
**Setup:**
Saves the snippet as `myproject/utils.py` or add the code to some place in your project with same ends.
**Use in a view:**
from myproject.utils import render_to_json
from django.contrib.admin.models import User
def json_view(request):
admin_user = User.objects.get(username='admin')
return render_to_json(
'json/example.json',
locals(),
)
**Update:**
This code can be used as complement to [http://www.djangosnippets.org/snippets/154/](JsonResponse snippet) too.
If you want to test a post request to a form, you need to give all input
fields, even if you just want to test if one value gets changed.
This snippets parses the HTML of a view and gives you a dictionary that
you can give to django.test.Client.
**Attention! This snippet must be ignored**, like [zgoda](http://www.djangosnippets.org/users/zgoda/) pointed with reason: already exists this functionality in `markup` contrib.
**Explanations:**
This template filter allows you to render easily a reStructuredText to **HTML** or another format it supports.
**Setup:**
Insert the snippet into an_app/templatetags/restutils.py.
**Use in template:**
`{% load restutils %}` and use it as following:
- `{{ entry.content|rest:"html" }}`
**Explanation:**
That template filters is util for combine boolean-return conditions using template tag `{% if %}`.
**Setup:**
Insert the snippet into an_app/templatetags/myutils.py.
**Use in template:** {% load myutils %} and use filters as following:
- `{% if 10|is_multiple_of:5 %}`
- `{% if 10|in_list:a_list_variable %}`
- `{% if user.username|is_equal:a_variable %}`
- `{% if user.username|is_not_equal:a_variable %}`
- `{% if a_variable_|is_lt:5 %}`
- `{% if a_variable_|is_lte:5 %}`
- `{% if a_variable_|is_gt:5 %}`
- `{% if a_variable_|is_gte:5 %}`
**Explanations:**
- the series "is_*_of" was created 'cos it's easier write: `{% if 10|is_day_of:date and user %}` than write: `{% ifequal date.day 10 %}{% if user %}...`
- the series "inc/dec" is not complete, but can the extended to day, hour, minute, etc as you needs. It's util to inc 10 months since 05/31/2006 by example and get a 2007's date :)
**Setup:**
Insert the snippet into an_app/templatetags/datetimeutils.py.
**Use in template:**
`{% load datetimeutils %}` and use filters as following:
- `{{ 30|is_day_of:a_date_time_variable }}`
- `{{ 11|is_month_of:a_date_time_variable }}`
- `{{ 2006|is_year_of:a_date_time_variable }}`
- `{{ 58|is_minute_of:a_date_time_variable }}`
- `{{ 23|is_hour_of:a_date_time_variable }}`
- `{{ a_date_time_variable|dec_year:2 }}`
- `{{ a_date_time_variable|dec_month:2 }}`
- `{{ a_date_time_variable|inc_year:2 }}`
- `{{ a_date_time_variable|inc_month:2 }}`
You have two models, one of which also has an image field. You want to get the data into a form and edit it. This also requires showing the url of the image, if there is one, on the form. This is a complete working example. No big deal, but for newbies, a complete working example could be valuable.
Provides the method from_related_ids, which lets you
select some objects by providing a list of related ids
(The huge difference to __in is that the objects have
to match al of the ids, not only one)
Model Example::
class Article(models.Model):
text = models.TextField()
tags = ManyToManyField('Tag')
objects = AllInManager()
Usage::
Article.objects.from_related_ids((1,2,3,4), 'tags')
The script that can be used to profile any Django-powered web-site and find how many SQL-queries are used per page, how heavy html-pages are, etc.
To use the the script it's enough to put django-profile.py somewhere in PYTHONPATH and call it from the directory that holds projects' settings.py.
For more info and examples please see:
[www.mysoftparade.com/blog/django-profile-sql-performance/](http://www.mysoftparade.com/blog/django-profile-sql-performance/)
[The Session documentation](http://www.djangoproject.com/documentation/sessions/) rightly warns of the dangers of putting a session ID into a query string. Sometimes, however, you have to do it - perhaps your client has mandated support for browsers with cookies disabled, or perhaps (as in my case) you're just dealing with a slightly broken client browser.
This middleware pulls a session ID out of the query string an inserts it into the cookies collection. You'll need to include it in your MIDDLEWARE_CLASSES tuple in settings.py, *before* the SessionMiddleware.
*Please* read my [full blog post](http://www.stereoplex.com/two-voices/cookieless-django-sessions-and-authentication-without-cookies) about for the dangers of doing this, and for full instructions and examples.
This snippet allows you to use @mako("templatename.mako") to define a mako template to use.
Your python method just has to return a dictionary that will be passed to mako's context, after the addition of the "request" variable to the dictionary. If you return a non-False non dictionary object, it will return that instead of trying to render the template. The **request** variable is automatically added to the template's context.
It also searches the current application's mako_templates/ subdirectory first before searching under the current directories mako_templates/, and does not use other application's mako_templates/ subdirectories at all.
On Mako exceptions, it will display the Mako error page when debugging is enabled (hoping for extensible exception handling in the future to keep consistency)
I got the idea from a [CherryPy tool](http://tools.cherrypy.org/wiki/Mako).
Generator to help make newforms classes a bit like inspectdb does for generating rough model code. This is a standalone script to go in your project directory with settings.py and called from the prompt. It looks up the model, and generates code to copy/paste into your app. Hopefully to make a building a custom form with a lot of fields a little easier. Every argument should be a model identifier of form appname.modelname.
Usage from the command line:
python form_gen myapp.MyModel myapp.MyOtherModel
I use this snippet when creating newforms with form_for_model and form_for_instance. Both do not have an argument that lets you filter out fields easily so I wrote this instead.
Typical use:
`form_class = form_for_instance(obj, fields=ignore_fields(model_class, ['field_name1']))`
This solves the problem with **choices** described [here](http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/)
Define your choices like this (in models.py):
statuses = MyChoices(BIDDING_STARTED=10, BIDDING_ENDED=20)
And then:
status = models.IntegerField(
default=statuses.BIDDING_STARTED,
choices=statuses.get_choices()
)