Login

All snippets

Snippet List

Monkey-patch Django's test client to return WSGIRequest objects

Testing low-level functionality sometimes requires a WSGIRequest object. An example of this is testing template tags. This will monkey-patch the test Client object to return WSGIRequest objects Normal Django behavior: >>> client.get('/') <HttpResponse > With this code, get the request object: >>> client.request_from.get('/') <WSGIRequest > Installation: For this to work, you simply need to import the contents of this file. If you name this file `clientrequestpatch.py`, do this inside your Django tests. from django.test.testcases import TestCase from myproject.test import clientrequestpatch

  • request
  • test
  • client
  • wsgi
  • wsgirequest
Read More

utf8-friendly dumpdata management command (no escape symbols)

Adds `--pretty` option to django `./manage.py dumpdata` command, which produces pretty utf8 strings instead of ugly unicode-escaped shit: $ ./manage.py dumpdata app.pricingplan --indent=1 [ { "pk": 1, "model": "app.pricingplan", "fields": { "name": "\u0411\u0430\u0437\u043e\u0432\u044b\u0439", } }, { "pk": 2, "model": "app.pricingplan", "fields": { "name": "\u0425\u0443\u044f\u0437\u043e\u0432\u044b\u0439", } } ]% ./manage.py dumpdata app.pricingplan --indent=1 --pretty [ { "pk": 1, "model": "app.pricingplan", "fields": { "name": "Базовый", } }, { "pk": 2, "model": "app.pricingplan", "fields": { "name": "Хуязовый", } } ]%

  • fixtures
  • management
  • dumpdata
Read More

Analogue template filter to removetags that also removes the content of the tag

Django's builtin `removetags` filter removes the supplied tags, but leaves the enclosed text alone. Sometimes you need the complete tag, including its content to go away. Example: <h1>Some headline</h1> <p>Some text</p> Applying `removetags:"h1"` to this html results in Some headline <p>Some text</p> while `killtags:"h1"` leaves <p>Some text</p>

  • filter
  • removetags
Read More

Automatic urls for static pages

Create in your template dir html files named example.static.html and with this snippet you can get the static page with the url /example/. If you put static file in a sub-directory, the url will be /sub-directory/example/ **Example:** `static_urls = StaticUrls()` `urlpatterns = patterns('', *static_urls.discover())` `urlpatterns += patterns('',` `(r'^admin/doc/', include('django.contrib.admindocs.urls')),` `(r'^admin/', include(admin.site.urls)),` `)`

  • urls
  • static
  • static files
  • url pattern
Read More

Import xls to satchmo

Just a quick solution to import product data from a excel spreadsheet to satchmo. Supports * hierarchical and multi categories * product attributes * product variations (configurable product, options) * product price * product image

  • excel-import
  • satchmo
Read More

Sane OneToOne getter

Since django insists on throwing a DoesNotExist rather than just returning a None from the far side of a null OneToOneField, I wrote this to have a sane way of getting those fields out without having to try/except all over in my code.

  • DoesNotExist
  • OneToOne
  • OneToOneField
Read More

Add CSS class template filter

Sometimes you want to add CSS classes to HTML elements that are generated by Django using their `__unicode__` representation, eg. you can output a form field with `{{ form.name }}`, but if you would like to add a certain CSS class to the outputted input or select tag you would have to assort to plain HTML. Using this filter you can simply do something like `{{ form.name|add_class:"span-4" }}` which will render an input like `<input type="..." name="..." class="span-4`.

  • django
  • template tag
  • css class
  • template filter
Read More

LogTrace

This small decorator will trace the execution of your code every time it enters or exits a decorated function (by thread) and will insert appropriate indent into the log file along with exception information.

  • decorator
  • logging
  • hax
  • trace
Read More

ModelMixin

Enables convenient adding of fields, methods and properties to Django models. Instead of: User.add_to_class('foo', models.CharField(...) User.add_to_class('bar', models.IntegerField(...) you can write: class UserMixin(ModelMixin): model = User foo = models.CharField(...) bar = models.IntegerField(...)

  • mixin
  • metaclass
  • util
  • metaprogramming
Read More

Comparing two json like python objects

Shows difference between two json like python objects. May help to test json response, piston API powered sites... Shows properties, values from first object that are not in the second. Example: import simplejson # or other json serializer first = simplejson.loads('{"first_name": "Poligraph", "last_name": "Sharikov",}') second = simplejson.loads('{"first_name": "Poligraphovich", "pet_name": "Sharik"}') df = Diff(first, second) df.difference is ["path: last_name"] Diff(first, second, vice_versa=True) gives you difference from both objects in the one result. df.difference is ["path: last_name", "path: pet_name"] Diff(first, second, with_values=True) gives you difference of the values strings.

  • django
  • json
  • piston
  • compare
Read More

Allow any view (probably a generic view) to accept POST variables into extra_context

Supposing you wanted to use a generic view, but you wanted to pass something over POST to show up in the resultant template. Perhaps you're creating a new object, and you want to pre-populate some hidden fields. `urlpatterns = patterns('django.views.generic.create_update', url(r'^obj/new$', view_post_vars_to_context(create_object), {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', 'post_vars_to_context':{'obj_id':'objID'}, extra_context: {:this":"that"}}), )` Now objID will be a variable in your template, with the value passed via POST in the variable obj_id. This is good for generic views, but there's no reason you couldn't use it for your own views if you really wanted, as long as you had an "extra_context" parameter. For security, since POST variables aren't cleansed automatically, this only accepts values of "_" and "-". If you feel confident, you can alter this to your needs.

Read More

Allow any view (probably a generic view) to accept captured URL variables into extra_context.

If your URL pattern looks like: `urlpatterns = patterns('django.views.generic.create_update', url(r'^obj/(?P<obj_id>\d+)/new_thing$', create_object, {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', extra_context: {:this":"that"}), )` You will receive an error, because the create_update view doesn't have a parameter called "obj_id". Supposing you want that variable in the URL, and furthermore let's say you wanted to do something with it in the template. With this function, you can wrap the view, and add the parameter capture_to_context, which maps URL variables to template variables: `urlpatterns = patterns('django.views.generic.create_update', url(r'^obj/(?P<obj_id>\d+)/new_thing$', view_url_vars_to_context(create_object), {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', 'url_vars_to_context':{'obj_id':'objID'}, extra_context: {:this":"that"}}), )` Now objID will be a variable in your template, with the value given to obj_id. This is good for generic views, but there's no reason you couldn't use it for your own views if you really wanted, as long as you had an "extra_context" parameter.

  • urls
  • views
Read More

3109 snippets posted so far.