Login

Tag "django"

Snippet List

Server Side Cursors for Django's psycopg2 Backend

Based on discussion on [http://thebuild.com/blog/2010/12/14/using-server-side-postgresql-cursors-in-django/](http://thebuild.com/blog/2010/12/14/using-server-side-postgresql-cursors-in-django/) and [http://thebuild.com/blog/2010/12/13/very-large-result-sets-in-django-using-postgresql/](http://thebuild.com/blog/2010/12/13/very-large-result-sets-in-django-using-postgresql/) but instead implements them via extending the psycopg2 backend which allows you to use all of django's machinery without having to resort to using raw cursors. Usage: qs = Model.objects.all() with server_side_cursors(qs, itersize=100): for item in qs.iterator(): item.value if random_reason_to_break: break Setup: In your own project create the package hierarchy myproject.db.backends.postgresql_psycopg2 and place the code in base.py. In your settings.py set the database ENGINE to be 'myproject.db.backends.postgresql_psycopg2'. If you using south you'll have to let it know its a postgresql_psycopg2 backend by adding to SOUTH_DATABASE_ADAPTERS (see south documentation). Note: Make sure your using psycopg >= 2.4 for efficient named (server side) cursor iteration.

  • django
  • server
  • backend
  • cursors
  • named
  • psycopg2
  • side
Read More

Keep Me Logged In for Django

Very simple middleware to implement "remember me" functionality. Updates the session once per day to keep user logged.

  • django
  • session
  • keep
  • logged
  • middlware
Read More

Django Number Input

This will give you a <input type='number'> field. This is helpful when you want to use HTML5 for newer browsers. Older browsers will just interpret this as <input type='text'>

  • django
  • django-forms
  • input-types
Read More

Decoupling models with cross-database relations

The snippet enables decoupling model classes, associated with a ForeignKey, for the purpose of separating them into two databases. Looking at the following example: class Reporter(models.Model): ... class Article(models.Model): reporter = models.ForeignKey(Reporter) We want to separate the `Reporter` and `Article` into two separate databases, but this won't work in Django because of the [cross model relations](http://docs.djangoproject.com/en/dev/topics/db/multi-db/#cross-database-relations). The solution is to use an ID field and not a `ForeignKey` one. This makes the access very uncomfortable. The above class will make this a bit less awkward. It doesn't support the [RelatedManager](http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager), but it will support accessing the related field as you normally would. The article class will look like this (assuming the reporter model id field is an `IntegerField`): class Article(DecoupledModel): reporter_id = models.IntegerField() _linked_fields = { 'reporter': Reporter, } Once you have an article object, you can access the reporter as you normally would for both read and writing. For example: my_reporter = article1.reporter article2.reporter = my_reporter

  • django
  • model
  • database
Read More

Template Tag of Django Image Thumb Creator

**You can save these codes into a templatetag file in your django app. Then use codes like these in your template files:** **************************************************************************** {% load *yourtags* %} ... <img src="{% thumb *yourmodel.picturefield* 200 300 0 %}"/> <img src="{% thumb *yourmodel.picturefield* 500 400 yes %}"/> ... The parameters are: imagefield ImageField width Integer height Integer rescale [1, yes, true, 0, no, false] **Some codes come from <djangosnippets.org>**

  • django
  • image
  • templatetag
  • thumb
Read More

is_in

I know in Django 1.2 we may acquire the same result using {% if value in arg %} but I need this filter in Django 1.1.

  • template
  • filter
  • django
  • contains
  • in
  • is
Read More

Model merging function

Generic function to merge model instances. Useful when you need to merge duplicate models together, e.g. for users. Based on http://djangosnippets.org/snippets/382/, with several enhancements: * *Type checking*: only Model subclasses can be used and testing that all instances are of same model class * *Handles symmetrical many-to-may*: original snippet failed in that case * *Filling up blank attrs of original when duplicate has it filled* * *Prepared to use outside of command-line*

  • django
  • model
  • generic
  • related
  • merge
Read More

Bypass CSRF check for Facebook canvas apps using POST for canvas

This assumes that you have a method called **decode_signed_request** which will validate the signed_request parameter and return None if the validation check fails. A similar method can be found here - https://github.com/iplatform/pyFaceGraph/blob/70e456c79f1ac1c7eddece03af323346a00481ef/src/facegraph/canvas.py

  • django
  • python
  • post
  • facebook
  • csrf
  • fb
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

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

GeoDjango maps in admin TabularInlines

This snippet adds support for OSM maps for GeometryField in Admin TabularInlines. The one possible issue with this snippet is that the OSMGeoInlineForm has to know about the parent ModelAdmin which it does through the code `model_admin_instance = admin.sites.site._registry[self.parent_model]` which won't work if you don't use the default model admin to register the model admin. I'll try and come up with a work around and edit the snippet. Due to the need to mess around with inline style sheets and IE not playing ball with just copying the innerHTML I've settled on using the jQuery.Rule plugin which I've included here as the last version published on the site was incompatible with jQuery 1.4.2 and I found a pathced version online, I also had to modify it due to the Django admin using the compatibility mode of jQuery so there is no global jQuery variable it's django.jQuery instead. 1. Create an osmgeo_inline.py file in your app and copy the top code into it. 2. Create the template file in a directory called admin within a template directory for your app, the template file must be called osmgeo_tabular_inline.html, and copy the middle code into it. 3. Create the jquery rule plugin file in your media or admin-media js directory and copy the bottom code into it. Don't forget to change the OSMGeoInlineForm's class Media's js = ('.....',) to the correct path to the file if need be. 4. In your admin.py you can create inline models using OSMGeoTabularInline just as you would TabularInline. Examples all based on the following in models.py from django.contrib.gis.db import models class MyModel(models.Model): name = models.CharField(max_length=64) route = models.LineStringField(srid=settings.WGS_SRID) class MySubModel(models.Model): mymodel = models.ForeignKey(MyModel) name = models.CharField(max_length=64) location = models.PointField(srid=settings.WGS_SRID) Example 1 - basic usage (admin.py): from django.contrib.gis.admin import OSMGeoAdmin from myapp.osmgeo_inline import OSMGeoTabularInline from myapp.models import MyModel, MySubModel class MySubModelInline(OSMGeoTabularInline): model = MySubModel class MyModelAdmin(OSMGeoAdmin): inlines = [MySubModelInline] admin.site.register(MyModel, MyModelAdmin) Example 2 - overriding the default map widget params and setting the inline map's centre point to match the main models map centre (admin.py): from django.contrib.gis.admin import OSMGeoAdmin from myapp.osmgeo_inline import OSMGeoTabularInline from myapp.models import MyModel, MySubModel class MySubModelInline(OSMGeoTabularInline): model = MySubModel class MyModelAdmin(OSMGeoAdmin): inlines = [MySubModelInline] params = {'map_width: 200, 'map_height': 200] def get_formset(self, request, obj=None, **kwargs): centre = None if obj is not None: centre = obj.route.centroid.transform(900913, clone=True) self.params['default_lon'] = centre.coords[0] self.params['default_lat'] = centre.coords[1] self.params['default_zoom'] = 12 return super(TrailSubmissionInlineBase, self).get_formset(request, obj, **kwargs) admin.site.register(MyModel, MyModelAdmin) I've not looked at StackedInlines because I don't use them but all that would be needed is to add a class OSMGeoStackedInline(StackedInline) that was a copy of OSMGeoTabularInline but with a template based on the StackedInline template - the javascript code in var initMap = function(row) would probably have to be adapted though.

  • django
  • admin
  • geodjango
  • map-widget
  • tabular-inlines
Read More

Improved command to generate UML diagrams of whole project or specified apps

example of use: 1. python manage.py yuml yourapp yoursecondapp --scruffy -s 75 -o test.png 2. python manage.py yuml justoneapp --scruffy -o test.pdf 3. generate whole project yuml : python manage.py yuml -a -o test.jpg 4. python manage.py yuml auth contenttypes sessions admin -o test.pdf [github repository](http://github.com/dzhibas/django-yuml)

  • django
  • command
  • basecommand
  • uml
  • yuml
Read More

213 snippets posted so far.