-1

Tryng to update User model and UserProfile model I diceded to generate a form with User and UserProfile models attributes, to update both with the same form. But when i subbmit the form to the view, the Users model is updating with no unicode render, example: (u'username' ), (u'name'). I dont understand why this happening, i check the utf-8 tag in both files.

forms.py

# -*- encoding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User

class UserProfileForm(forms.Form):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(UserProfileForm, self).__init__(*args, **kwargs)

    username = forms.CharField(required=True,
        widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))

    name = forms.CharField(required=True,
        widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))

    lastname = forms.CharField(required=True,
        widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))

    email = forms.CharField(required=True,
        widget = forms.EmailInput(attrs={'class':'input', 'autocomplete':'off'}))

    change_password = forms.BooleanField(required=False,widget = forms.CheckboxInput())

    password1 = forms.CharField(required=False, min_length = 8,
        widget = forms.PasswordInput(render_value=False, attrs={'class':'input hidden'}))

    password2 = forms.CharField(required=False, min_length = 8,
        widget = forms.PasswordInput(render_value=False, attrs={'class':'input hidden'}))

    institution = forms.CharField(required=False,
        widget = forms.TextInput(attrs={'class':'input', 'autocomplete':'off'}))

    logo = forms.ImageField(required=False)

    def clean_username(self):
        username = self.cleaned_data.get('username').lower()
        print username
        try:
            u = User.objects.exclude(pk=self.request.user.id).get(username__iexact=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(u'Este nombre de usuario ya existe.')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        try:
            e = User.objects.exclude(pk=self.request.user.id).get(email__iexact=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError(u'ya existe un usuario asociado a este correo electrónico.')

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if not(password1 and password2):
            pass
        elif not password2:
            raise forms.ValidationError("Debes confirmar la contraseña")
        if password1 != password2:
            raise forms.ValidationError("Las contraseñas no coinciden")
        return password2

currently the view is only updating User model:

class UpdateProfile(FormView):
    model = User
    template_name = 'general/perfil.html'
    form_class = UserProfileForm

    def get_initial(self):
        initial = super(UpdateProfile, self).get_initial()
        initial['username'] = self.request.user.username
        initial['name'] = self.request.user.first_name
        initial['lastname'] = self.request.user.last_name
        initial['email'] = self.request.user.email
        try:
            profile = UserProfile.objects.get(user=self.request.user)
        except UserProfile.DoesNotExist:
            profile = None
        if profile:
            initial['institution'] = profile.institution    
        return initial

    def get_form_kwargs(self):
         kwargs = super(UpdateProfile, self).get_form_kwargs()
         kwargs.update({'request' : self.request})
         return kwargs

    def form_valid(self, form):
        user = get_object_or_404(User, pk= self.request.user.id)
        user.username = form.cleaned_data['username'],
        user.first_name = form.cleaned_data['name'],
        user.last_name = form.cleaned_data['lastname'],
        user.email = form.cleaned_data['email']
        if form.cleaned_data['change_password']:
            user.password = form.cleaned_data['password1']
        user.save()
        return HttpResponseRedirect('/profile')

could be a problem with form.cleaned_data method? Any ideas?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
andre
  • 192
  • 2
  • 12
  • "the Users model are updating with no unicode render" What? – Ignacio Vazquez-Abrams Nov 18 '14 at 04:16
  • yes, for example when i type in the name input Andrés and submit the form, the User models update with name (u'Andr\xe9s',) – andre Nov 18 '14 at 04:19
  • Oh dear. You seem to be saving passwords as plain text in your database. **Never, ever, ever, ever** do that. Anyway, Django includes a perfectly good authentication framework which you should almost always use, rather than rolling your own. – Daniel Roseman Nov 18 '14 at 09:08
  • I thought that save method internally manage password hash. I will fixed immediately, thanks for your advice. – andre Nov 18 '14 at 17:02

1 Answers1

1

Look veeery closely at the following lines:

user.username = form.cleaned_data['username'],
user.first_name = form.cleaned_data['name'],
user.last_name = form.cleaned_data['lastname'],

Do you see it?

Yes, it's that comma at the end. It's creating a tuple. Stop doing that.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358