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), …
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 …
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 …
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. …
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, …
# 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"
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 …
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
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 …
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
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
#!/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
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>, …
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
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
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 …
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 …
SELECT count(email),email FROM auth_user GROUP BY email HAVING count(email) > 1;