Python and Django

08 Oct, 13

Automatically create OneToOne related object

If you have a parent model that has OneToOne relation to some other model and you want this child model to be created upon parent model creation you need to install django-annoying package like this:

1
  1. pip install django-annoying

enable annoying app and replace your models.OneToOneField with AutoOneToOneField like ...

Read now
29 Sep, 13

ImageField: overwrite file if file with the same name exists

Create a separate file storage.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  1. from django.core.files.storage import FileSystemStorage
  2. from django.conf import settings
  3. import os
  4. class OverwriteStorage ...
Read now
28 Sep, 13

Django admin: How to display a field that is marked as editable=False in the model?

Use Readonly Fields, example:

1
2
  1. class MyModelAdmin(admin.ModelAdmin):
  2. readonly_fields=('first',)
Read now
28 Sep, 13

How to get edit url for model instance

Use this:

1
  1. urlresolvers.reverse("admin:%s_%s_change" % (self.model._meta.app_label, self.model._meta.module_name), args=(object_id,))

to redirect to object edit page after performing some action, use this snippet:

1
  1. return redirect(urlresolvers.reverse("admin:%s_%s_change" % (self.model._meta.app_label, self.model._meta ...
Read now
23 Sep, 13

How to run an arbitrary script in the context of the Django project?

The easiest way to do this is to set up your script as a manage.py subcommand. Here's how to do that:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  1. from django.core.management.base import NoArgsCommand, make_option
  2. class Command(NoArgsCommand):
  3. help = "Whatever you want to ...
Read now