A Form and ModelForm which provides the ability to specify certain fields as readonly, meaning that they will display their value as text wrapped with a tag. The user is unable to edit them, and they are protected from POST data insertion attacks.
The recommended usage is to place a NewMeta inner class on the form, with a readonly attribute which is a list or tuple of fields, similar to the fields and exclude attributes on the Meta inner class.
class MyForm(ReadonlyForm):
foo = forms.TextField()
bar = forms.T...
class HiddenInputColumn(tables.Column):
def __init__(self, *args, **kwargs):
kwargs['attrs'] = {'th': {'style': 'display:none;'},
'td': {'style': 'display:none;'}}
super(HiddenInputColumn, self).__init__(*args, **kwargs)
def render(self, value):
return mark_safe('<input type="hidden" name="{}" value="{}" />'.format(self.verbose_name, value))
html
<select onchange="this.form.submit()">
...
</select>
django-crispy-forms
self.helper.layout = Layout(
Field('select_field', onchange="this.form.submit()")
)
django-crispy-forms
self.helper.layout = Layout(
Field('select_field', onkeyup="this.form.submit()")
)
pip install django-reset-migrations
manage.py reset_migrations app1 app2
Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”. Django provides django.contrib.staticfiles to help you manage them.
Usually the settings file will have:
STATIC_URL = '/static/'
You can then use the following in your template:
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
Which serves up the file off of :
my_app/static/my_app/example.jpg.
SessionAuthentication method: This method uses the session cookie (which is set through the normal Django login and logout views) to check out if there’s an authenticated user and get his username. This method works only in the same session (browser window) as the one that actually did the login but this should be enough for most cases.
After you log in with Django, your authentication information is saved to the “session”_. The session is a bucket of information that the Django application saves about your visit — to distingui...
REST framework provides two wrappers you can use to write API views.
These wrappers provide a few bits of functionality such as making sure you receive Request instances in your view, and adding context to Response objects so that content negotiation can be performed.
The wrappers also provide behaviour such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exception that occu...
Nearly all modern regular expression engines support numbered capturing groups and numbered backreferences. Long regular expressions with lots of groups and backreferences may be hard to read. They can be particularly difficult to maintain as adding or removing a capturing group in the middle of the regex upsets the numbers of all the groups that follow the added or removed group.
Python's re module was the first to offer a solution: named capturing groups and named backreferences.
(?P<name>group)
captures the match of group into t...
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 unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import...
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 necessary to add the apps directory to the path, too.
from os.path import abspath, dirname, join
PROJECT_ROOT = abspath(dirname(__file__))
sys.path.append(join(PROJECT_ROOT, "apps"))
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)...
class PersonColumn(tables.Column):
attrs = {
'td': {
'data-first-name': lambda record: record.first_name
'data-last-name': lambda record: record.last_name
}
}
def render(self, record):
return '{} {}'.format(record.first_name, record.last_name)
class Table(tables.Table):
person = PersonColumn()
Install
pip install django-widget-tweaks
INSTALLED_APPS = [
...
'widget_tweaks',
...]
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_processors in your template setting OPTIONS.
example from: stackoverflow
from django.db import models
from django.db import transaction
class MyModel(models.Model):
# model definition
def save(self, *args, **kwargs):
transaction.set_autocommit(False)
try:
super(MyModel, self).save(*args, **kwargs)
foo() # do_other_things
except:
transaction.rollback()
raise
else:
...
import utils
from django.utils import timezone
from app import models
def orm_bulk_create(n_records):
instances = [
models.TestModel(
field_1=i,
field_2=str(i),
field_3=timezone.now(),
)
for i in xrange(0, n_records)
]
models.TestModel.objects.bulk_create(instances)
if __name__ == '__main__':
utils.timed(orm_bulk_create
Every field you add to the values() clause, will be used to create the group by query
City.objects.values('name', 'country__name').annotate(Sum('population'))
Poll.objects.get(
Q(question__startswith='Who'),
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
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(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
objects = models.Manager() # The default manager.
dahl_objects = DahlBookManager() # The Dahl-specific manager.
Primary Key
from django.db import models
class Fruit(models.Model):
name = models.CharField(max_length=100, primary_key=True)