Related cards:
django primary key
Primary Key
from django.db import models
class Fruit(models.Model):
name = models.CharField(max_length=100, primary_key=True)
django DRF Permissions
Settings
global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK.
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for una...
django management commands
Management Commands
Add a management/commands directory to the application. Django will register a manage.py command for each Python module in that directory whose name doesn’t begin with an underscore.
Example
from django.core.manageme...
django transaction.set_autocommit(False)
example from: stackoverflow
from django.db import models
from django.db import transaction
class MyModel(models.Model):...
django tables2 installation
Django-tables2 is Available on pypi and can be installed using pip:
pip install django-tables2
After installing, add 'django_tables2' to INSTALLED_APPS and make sure that 'django.template.context_processors.request' is added to the context_proces...
django-tables2
hidden input column
class HiddenInputColumn(tables.Column):
def __init__(self, *args, **kwargs):
kwargs['attrs'] = {'th': {'style': 'display:none;'},
'td': {'style': 'display:none;'}}
super(Hi...
django admin action
Sample duplicate event
This example makes use of clearing the id field (primary key) and then saves the record to produce a duplicate of the record. The user can select as many records from the admin panel and it will duplicate each in the sel...
django apps in subfolder
sample manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
# Add the apps directoriy to Python's path. In production it will
# be n...
django rename app
Before renaming
Always migrate databases before changing the app name.
manage.py makemigrations
when you see the following message then it is safe to proceed with renaming the app.
No changes detected
Fixed table names
...
django query managers
managers
# First, define the Manager subclass.
class DahlBookManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(author='Roald Dahl')
# Then hook it into the Book model explicitly.
class Book(mod...