1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class Post(models.Model): name = models.CharField() subtitle = models.CharField(blank=True) content = models.TextField() created_at = models.DatetimeField() user = models.ForeignField(User)
class PostForm(forms.ModelForm): error_css_class = 'error' required_css_class = 'required' another_field = forms.DateField( required=True, label="Custom Field Name", label_suffix=":", initial="abc", help_text="除Model本身字段以外的额外的字段", error_messages=[] validators=[] disabled=False widget={ } ) choice_field = forms.ModelChoiceField(queryset=MyChoices.objects.all())
class Meta: model = Post fields = ("name", "subtitle", "content", "another_field") labels = {"name": "Input the Name"} help_texts = {"name": "Enter a correct name"} error_messages = {"name": { "max_length": "字段太长了" }} field_classes = { "name": "my_text" } widgets = { "created_at": forms.TextInput(attrs={ "type": "date", "class": "my-class custom-class" "placeholder": "设置placeholder" }), "description": forms.Textarea(attrs={"rows": 1, "cols": 20}) }
def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields["name"].label = "Post Name" self.fields['user'].queryset = User.objects.filter(id__in[1,2,3]) self.fields['my_choice_field'] = forms.ChoiceField(choices=[1,2,3]) def clean_name(self): data = self.cleaned_data['name'] if 'test' in data: raise ValidationError(_('Invalid name')) return data
|