Models
Model constraints
As of aug. 2009, Django doesn't have a way of specifying constraints in the model. See here.
Forms
override possible options of a modelchoice field in a form
customize the queryset of the field after calling the base class __init__
method:
def __init__(self, ...):
...
self.fields['course_assistant'].queryset = User.objects.filter(
belong_to_school__school=user.current_school,
belong_to_school__status=STATUS_ACTIVE,
belong_to_school__is_teacher=True,
)
Change default widget of a ModelForm Field
Don't do it as suggested in Django's official docs about it; if you do it that way, the new widget won't the default values, help text, labels and other stuff already defined in the model field. Do it overriding only the widget attribute, like this
[[!format py """ from django import forms from mysite.polls.models import Poll
class PollForm(forms.ModelForm): def init(self, args, **kwargs): super(PollForm, self).init(args, **kwargs) self.fields['question'].widget = forms.Textarea()
class Meta:
model = Poll
"""]]
Obtained from here