

If you want to get in touch with German djangoers, you can join the
#django-de
IRC channel on irc.freenode.net
. Also you can subscribe to their blogs at django-de.org.
Aidas Bendoraitis on development with Django, Python, and JavaScript. I am migrating this blog to djangotricks.com
#django-de
IRC channel on irc.freenode.net
. Also you can subscribe to their blogs at django-de.org.
datetime.datetime(2008, 5, 27, 17, 0)
input[type=checkbox]
and similar in CSS are not supported by IE so people working with templates and CSS obviously need some other way to select and style specific types of input fields.<span class="form_checkbox">
{{ form.is_privacy_policy_confirmed }}
</span>
class FormExample(forms.Form):
is_privacy_policy_confirmed = forms.BooleanField(
required=True,
widget=CheckboxInput(attrs={'class': 'form_checkbox'}),
)
render
of the Widget
class draws the input field in HTML. As it takes a parameter attrs
for additional input field attributes, my idea was to create a decorator which modifies the incoming parameters and adds a CSS class "form_TYPE"
, where TYPE
is the input field type.input_type
of the Widget class is used for forming the CSS class name (N.B. not all widgets have this attribute).from django.newforms.widgets import Input, CheckboxInput, RadioSelect, CheckboxSelectMultiple
### adding class="form_*" to all html input fields ###
def add_css_class(css_class=""):
def modify_input_class(function):
_css_class = css_class
def new_function(*args, **kwargs):
arg_names = function.func_code.co_varnames
new_kwargs = dict(zip(arg_names, args))
new_kwargs.update(kwargs)
css_class = _css_class or "form_%s" % getattr(
new_kwargs['self'],
"input_type",
"undefined",
)
self = new_kwargs.pop("self")
attrs = getattr(self, "attrs", None) or {}
if "class" in attrs:
css_classes = attrs["class"].split()
if css_class not in css_classes:
css_classes.append(css_class)
attrs["class"] = " ".join(css_classes)
else:
attrs["class"] = css_class
self.attrs = attrs
return function(self, **new_kwargs)
return new_function
return modify_input_class
Input.render = add_css_class()(Input.render)
CheckboxInput.render = add_css_class("form_checkbox")(CheckboxInput.render)
RadioSelect.render = add_css_class("form_radio")(RadioSelect.render)
CheckboxSelectMultiple.render = add_css_class("form_checkbox")(CheckboxSelectMultiple.render)
models.py
file in your project.css_class
isn't recognized by the sub-child function new_function
directly although the scope of the variable css_class
should let it be accessed there. Anyway, the value got easily accessible when I reassigned it to another variable like _css_class
in the child function modify_input_class
.attrs
argument from the decorated function as it was not clear whether it would be passed as a positional or as a named argument. The first three lines of the function new_function
collects all the incoming arguments to a dictionary new_kwargs
. They can be modified and then passed to the original function to decorate.from django.conf import settings
SOME_SETTING = getattr(settings, "SOME_SETTING", "default value")
template
to the view in your urls.py file.from datetime import datetime, timedelta
from django.views.generic.simple import direct_to_template
def direct_to_js_template(request, *args, **kwargs):
response = direct_to_template(request, *args, **kwargs)
response['Content-Type'] = "application/x-javascript"
now = datetime.utcnow()
response['Last-Modified'] = now.strftime('%a, %d %b %Y %H:%M:%S GMT')
expires = now + timedelta(0, 2678400)
response['Expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S GMT')
return response
FIELD_CHOICES = SomeModel._meta.get_field("field_name").get_choices()
FIELD_CHOICES[0] = ("" _("- Choose One -"))
del FIELD_CHOICES[0]
new_instance = SomeModel()
new_instance.field_name_id = form.cleaned_data['field_name']
new_instance.save()
def get_related_queryset(model, field_name):
"""
Get the queryset for the choices of the field in a model
Example:
objects = get_related_queryset(SomeModel, "field_name")
"""
f = model._meta.get_field(field_name)
qs = f.rel.to._default_manager.complex_filter(f.rel.limit_choices_to)
return qs
auth
for authentication, admin
for basic data manipulation, or flatpages
for the dynamic content that tends to be rarely changed. Sometimes you want to use them, but their functionality doesn't completely fit your needs.INSTALLED_APPS
setting. As Python is an interpreted language and all methods and properties are public, you can access and change them on the fly."django.contrib.auth"
in the INSTALLED_APPS
.#!/usr/bin/python
# -*- coding: UTF-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Group
def modify_group_class():
""" A function modifying the contributed Group model """
# modifying the verbose names
Group._meta.verbose_name = _("Role")
Group._meta.verbose_name_plural = _("Roles")
def display_users(group):
""" A function displaying users for a group """
links = []
for user in group.user_set.all():
links.append(
"""<a href="/admin/auth/user/%d">%s</a>""" % (
user.id,
("%s %s" % ( # show the real name
user.first_name,
user.last_name, # or the username
)).strip() or user.username,
)
)
return "<br />".join(links)
display_users.allow_tags = True
display_users.short_description = _("Users")
# attaching the new function to the Group model
Group.display_users = display_users
# changing the list_display for the Group model
Group._meta.admin.list_display = ("__str__", "display_users")
modify_group_class()
Group._meta
returns the Meta
class and Group._meta.admin
returns the Admin
class for the Group
model. You can prove it to yourself by browsing objects in Django shell aka Python IDE.camelCase
or by_underscores
, but not mixed up in one project. Use triple double quotes """for documentation of functions"""
and triple single quotes '''for commenting some code out'''
. For readability it is convenient to limit all your lines to 80 symbols. If a statement is very long, put it inside the brackets and then separate into different lines (this is easier to manage than having a backslash (\) before the new line symbol). When debugging and adding print statement or similar, also add some comment like # DEBUG
, which can be easily found later. If there is something to improve in the code, add a comment like # TODO
with the description of possible improvement. These words are easily findable later. If you have a long list, tuple or dictionary of items, or a function with many arguments which don't fit into the limit of 80 symbols, separate the items with each per line, indented by one tab. Use comma even after the last item unless it is **kwargs
. Put the closing bracket after all. This will let you easily rearrange the order or amount of items later.view = my_special_view(
request,
arg1,
arg2,
arg3,
)
dir()
function for all objects to check the available methods and attributes, use the __dict__
attribute for model instances to check its field values, write for-loops for listing out specific attributes from model instances from different querysets. Interaction and visual representation always gives you some better understanding about the architecture than just Django documentation. Also when something is not clear, don't be afraid to read the source. Take advantage of Django being an open source project.>>> from django.contrib.auth.models import User
>>> for u in User.objects.all():
... u.__dict__
...
{'username': u'aidas', 'first_name': u'Aidas', 'last_name': u'Bendoraitis', 'is_active': 1, 'email': u'', 'is_superuser': 0, 'is_staff': 0, 'last_login': datetime.datetime(2008, 2, 27, 13, 43, 58), 'password': u'sha1$e55b5$9aa9485f4ad6fc7947e80b63e6d56519c73ac5bb', 'id': 1L, 'date_joined': datetime.datetime(2007, 3, 30, 20, 56, 7)}