Django: Validation error in Admin

前端 未结 1 1117
失恋的感觉
失恋的感觉 2021-01-20 19:43

NEWBIE ALERT!

background:

For the first time, I am writing a model that needs to be validated. I cannot have two Items that have ov

相关标签:
1条回答
  • 2021-01-20 20:34

    For Django 1.2 see http://docs.djangoproject.com/en/dev/ref/forms/validation/#using-validation-in-practice.

    In versions prior to 1.2 you would have to make your own model form for your admin and put your validation methods there! http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute

    from django import forms
    from models import Item
    
    class ItemForm(forms.ModelForm):
    
       class Meta:
           model = Item
    
       def clean(self, value):
           data = self.cleaned_data
           start = data['startDate']
           end =  data['endDate']
           try:
               item = Item.objects.get(Q(startDate__range=(start,end))|\
                                       Q(endDate__range=(start,end))|\
                                       Q(startDate__lt=start,endDate__gt=end))
               raise forms.ValidationError('.....')
           except:
               pass
    
       return data 
    

    Then put in your admin form=ItemForm and make sure to define the form somewhere before! For a more detailled description see http://www.jroller.com/RickHigh/entry/django_admin_validation_of_multiple.
    Further to assort to django conventions you should name your fields eg. end_date and not endDate. Guess you will not even need to specify their verbose_name then anymore!

    0 讨论(0)
提交回复
热议问题