2011-04-04 14 views
8

tengo un modelo de eventos que me gustaría hacer la siguiente regla de validación en adelante, en un método personalizado def clean(self): en el modelo:django. la adición de un campo a form.errors en una costumbre limpia() método

def clean(self): 
    from django.core.exceptions import ValidationError 
    if self.end_date is not None and self.start_date is not None: 
     if self.end_date < self.start_date: 
      raise ValidationError('Event end date should not occur before start date.') 

Lo cual funciona bien, excepto que me gustaría destacar el campo self.end_date en la interfaz de usuario del administrador, nominándolo de alguna manera como el campo que tiene errores. De lo contrario, solo recibiré el mensaje de error que aparece en la parte superior del formulario de cambio.

Respuesta

11

El docs explica cómo hacerlo en la parte inferior.

proporcionan ejemplo:

class ContactForm(forms.Form): 
    # Everything as before. 
    ... 

    def clean(self): 
     cleaned_data = self.cleaned_data 
     cc_myself = cleaned_data.get("cc_myself") 
     subject = cleaned_data.get("subject") 

     if cc_myself and subject and "help" not in subject: 
      # We know these are not in self._errors now (see discussion 
      # below). 
      msg = u"Must put 'help' in subject when cc'ing yourself." 
      self._errors["cc_myself"] = self.error_class([msg]) 
      self._errors["subject"] = self.error_class([msg]) 

      # These fields are no longer valid. Remove them from the 
      # cleaned data. 
      del cleaned_data["cc_myself"] 
      del cleaned_data["subject"] 

     # Always return the full collection of cleaned data. 
     return cleaned_data 

para su código:

class ModelForm(forms.ModelForm): 
    # ... 
    def clean(self): 
     cleaned_data = self.cleaned_data 
     end_date = cleaned_data.get('end_date') 
     start_date = cleaned_data.get('start_date') 

     if end_date and start_date: 
      if end_date < start_date: 
       msg = 'Event end date should not occur before start date.' 
       self._errors['end_date'] = self.error_class([msg]) 
       del cleaned_data['end_date'] 
     return cleaned_data 
+0

Ah, ya veo. Apliqué mi método 'clean()' directamente al Modelo. Entonces, ¿esto debe ocurrir en el formulario utilizado por ModelAdmin? – Daryl

+0

@Daryl http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin podría ayudarlo. En otra nota, la aceptación de tu respuesta es baja. Es posible que desee trabajar en eso si quiere más ayuda con sus preguntas en general. – DTing

+0

Gracias @kriegar! Haré, todo funciona bien. – Daryl

13

De Django 1.7 se puede añadir directamente error para el campo particular mediante el uso de add_error método. Django docs

form.add_error('field_name', 'error_msg or ValidationError instance') Si el field_name es None se añadirá el error de non_field_errors.

def clean(self): 
    cleaned_data = self.cleaned_data 
    end_date = cleaned_data.get('end_date') 
    start_date = cleaned_data.get('start_date') 

    if end_date and start_date: 
     if end_date < start_date: 
      self.add_error('end_date', 'Event end date should not occur before start date.') 
      # You can use ValidationError as well 
      # self.add_error('end_date', form.ValidationError('Event end date should not occur before start date.')) 

    return cleaned_data 
Cuestiones relacionadas