Working Ninja
2018-09-26T07:41:35

By default, a ModelForm is populated with all its objects from the database. Sometimes it's desirable to limit these results as they are returned to the view. After setting up our ModelForm (forms.py) there is only one thing we need to do to make this happen. Within our view (views.py), …

READ MORE

2018-04-22T10:28:39

If you've ever touched a date or time related field via the Django API, you'll have noticed the big warning that the date and/or time is not localized. While the warning is nice there isn't much more in the way of how to localize the time. Here are two ways …

READ MORE

2017-11-18T10:17:05

This post outlines that bare minimum that needs to be done to set up a post_save signal using Django. One rationale behind using a signal is that a model instance can be saved without the user having to wait for additional code to process (e.g. consuming an external API). This …

READ MORE

2017-08-29T17:47:18

Using the ManifestStaticFilesStorage storage backend alters the filename of our static files. For example, style.css becomes something like style.3d94ea84cd8a.css. When collectstatic is run and finds a file that has changed, the MD5 portion of the filename will be updated (style.3d94ea84cd8a.css -> style.1d74ea7349df.css). This prevents browsers and other caching technologies (e.g. …

READ MORE

2017-08-24T20:59:14

Here's a custom manager for a class (Change) that gets all approved changes where "today's date" falls between the Change.start_date and Change.end_date.

# models.py import datetime ... # Custom Change Manager that only pulls active, approved changes class ApprovedChanges(models.Manager): def get_queryset(self): today = datetime.date.today() return super(ApprovedChanges, self).get_queryset().filter( approved=True, …

READ MORE

2017-08-24T07:47:57
# Simple List ', '.join([author.name for author in authors]) # Django ', '.join([author.name for author in book.author_set.all()])

Both will output "Author Name, Author 2 Name, ..., Author x Name"

READ MORE

2017-05-29T10:58:45

I just started my first Django project with Python 3 in earnest. One of the first things I have noticed is that reload isn't available by default from the Django shell. It needs to be imported:

>>> from importlib import reload >>> reload(<module>)

This became a pretty …

READ MORE

2017-03-23T17:22:08

Here's a simple way to count lines of code via the command line that I recently used for a Django project:

find . -name '*.py' -not -path "*/migrations/*" | xargs wc -l

or

wc -l **/*.py

Source: http://stackoverflow.com/questions/1358540/how-to-count-all-the-lines-of-code-in-a-directory-recursively#1358573

READ MORE

2017-02-10T16:39:53

Somehow, somewhere, something happened to my migrations. It had been a few months since I had edited my models.py file and out of the blue I ended up with an issue adding an additional field to a model. I search around Stack Overflow and found a great answer that resolves …

READ MORE

2016-11-11T16:55:21
import json polls = Poll.objects.all() # Convert our QuerySet into a list so polls can be serialized print json.dumps(list(p), indent=2) JsonResponse({'polls': list(polls)})

Source: http://stackoverflow.com/questions/7650448/django-serialize-queryset-values-into-json

READ MORE

2016-11-03T20:05:28
import json import psycopg2 from psycopg2.extras import RealDictCursor cursor = conn.cursor(cursor_factory=RealDictCursor) objects = cursor.fetchall() print json.dumps(objects, indent=2) # Django #JsonResponse({'objects': objects})

Source: https://www.peterbe.com/plog/from-postgres-to-json-strings

READ MORE

2016-09-06T07:51:45
#!/usr/bin/env python import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django django.setup() from app.models import Class # Your scripting here.

Sources:
https://docs.djangoproject.com/en/1.10/intro/tutorial02/#playing-with-the-api
https://docs.djangoproject.com/en/1.10/topics/settings/#on-the-server-mod-wsgi

READ MORE

2016-03-30T21:57:36

I was attempting to make a directory listing of sorts earlier tonight and couldn't think up a clean solution. Some surfing on the world wide web offered up a quick template tag solution.

For example, say we have a list of objects (Person) from our app's view, [<Person: Doe>, …

READ MORE

2016-02-04T08:04:04
class AbstractClass(models.Model): common_attribute = models.CharField() class Meta: abstract = True class SpecializedClass(models.Model): specialized_attribute = models.CharField() class Meta: abstract = True class AnotherSpecializedClass(models.Model): another_specialized_attribute = models.CharField() class Meta: abstract = True class MultipleInheritance(AbstractClass, SpecializedClass): pass class TripleMulitpleInheritance(AbstractClass, SpecializedClass, AnotherSpecializedClass): pass

Sources: https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes,
https://docs.djangoproject.com/en/1.9/topics/db/models/#multiple-inheritance

READ MORE

2016-01-11T22:52:32

Note: the following commands drop all data from the database.

$ rm -rf db.sqlite3 $ rm -rf app/migrations/* $ ./manage.py makemigrations --empty app $ ./manage.py makemigrations $ ./manage.py migrate $ ./manage.py createsuperuser

READ MORE

2015-12-05T17:32:59

I needed to create a slew of objects for a project I was working on. Lots of tedious and error prone work. But wait, I'm using a computer. Automation to the rescue!

I wrote my script by first importing what I needed from Django (User and the Appointment model …

READ MORE

2015-11-27T11:40:34

Static files for an app follow the following directory structure my_app/static/my_app and are picked up by ./manage.py collectstatic when ready to deploy. If you're wanting to use static files that span multiple apps, update your settings.py to include the following:

STATICFILES_DIRS = ( os.path.join(BASE_DIR, "project_static"), )

Temping …

READ MORE

2015-10-14T10:22:24
SELECT count(email),email FROM auth_user GROUP BY email HAVING count(email) > 1;

READ MORE