简体   繁体   中英

Validate Django Choices with Accents in ModelForms

I have this model in Django:

@python_2_unicode_compatible
class Student(models.Model):
    CHOICES = (('Graduación', 'Graduación'),
               ('Baja Temporal', 'Baja Temporal'),
               ('Expulsión', 'Expulsión'))
    persona = models.OneToOneField(Persona)
    enrollemente_code = models.CharField(max_length=10, unique=True)
    prev_school = models.CharField(max_length=256, blank=True, null=True)
    medical_notes = models.TextField(null=True, blank=True)
    enrollement_date = models.DateField()
    egress_date = models.DateField(blank=True, null=True)
    egress_reason = models.CharField(max_length=64, choices=CHOICES,
                                 blank=True, null=True)
    egress_comments = models.TextField(null=True, blank=True)

    def __str__(self):
        return self.persona.get_full_name()

And I created this ModelForm:

class UnenrollForm(ModelForm):
    class Meta:
        model = Student

        labels = {
            'egress_date': 'Fecha',
            'egress_reason': 'Razón de Baja',
            'egress_comments': 'Comentarios',
        }

        widgets = {
        'egress_comments': Textarea(attrs={'rows': 3}),
    }

    exclude = ['persona', 'enrollemente_code', 'prev_school',
               'medical_notes', 'enrollement_date']

When I call the unenrollform.is_valid() at my View, I get this warning:

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal '==': infix(10, lambda context, x, y: x.eval(context) == y.eval(context)),

And the egress_reason field is considered wrong.

Do you know any way to validate this? Or a turn around?

Note that in the CHOICES array, your entries are supposed to be (code, label) . The code is what Django actually uses internally and in the DB, whereas the label is purely presentational.

Here, it would make sense for you to follow that convention. Among other things, this will make internationalizing your project easier down the road (if needed). Incidentally, it should also make your problem go away:

CHOICES = (('graduated', 'Graduación'),
           ('temporary', 'Baja Temporal'),
           ('expelled', 'Expulsión'))

Note that if you already have data in your DB, you're going to have to somehow migrate it.


Now, depending on which version of Python you're using, it's also a good idea to ensure your non-ASCII strings are declared as unicode (otherwise, you're leaving it up to Python to guess their encoding at runtime).

Specifically, in Python 2, you should do the following (in Python 3, you don't need to do anything):

CHOICES = (('graduated', u'Graduación'),
           ('temporary', u'Baja Temporal'),
           ('expelled', u'Expulsión'))

Also, make sure you to declare the encoding of your file. The first line should be:

#coding:utf-8

Note that this assumes that your file is encoded in utf-8 , but that's a pretty safe assumption.

I am using python 2.7, and i resolved it adding an 'u' to the strings, for example

u'Explicación'

Applied to labels

labels = {
            'anio': _(u'Escriba el año'),
            'tarjetacirculacion': _(u'# de tarjeta de circulación'),
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM