jeudi 2 mars 2017

Django and python 2.7 issue with unicode in form error

I'm start new project in TDD idea so first I wrote tests. But I have a problem with utf (I think)

I have simple login form

from django.utils.translation import ugettext_lazy as _

ERRORS_MESSAGES = {
    'not_active': _(u"Użytkownik nie jest aktywny"),
    'user_not_exist': _(u"Użytkownik o podanym loginie już istnieje")
}


class LoginForm(forms.Form):
    username = forms.CharField(max_length=50)
    password = forms.CharField(max_length=50, widget=forms.PasswordInput)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        if not user:
            raise forms.ValidationError(ERRORS_MESSAGES['user_not_exist'])
        if not user.is_active:
            raise forms.ValidationError(ERRORS_MESSAGES['not_active'])
        return self.cleaned_data

And in test:

user = User.objects.create(
    username='asd', password='asd', email='asd@ad.asd'
)
form = LoginForm(data={'username': 'asd', 'password': 'asd'})
self.assertEqual(form.is_valid(), False)
print "ERRORS:", form.errors['__all__']
self.assertIn(ERRORS_MESSAGES['not_active'], form.errors)

And console output:

# here, char 'ż' looks fine, 
ERRORS: <ul class="errorlist nonfield"><li>Użytkownik o podanym loginie już istnieje</li></ul>
# but next:
self.assertIn(ERRORS_MESSAGES['not_active'], form.errors)

AssertionError: not found in {'all': [u'U\u017cytkownik o podanym loginie ju\u017c istnieje']}

Aucun commentaire:

Enregistrer un commentaire