Найти - Пользователи
Полная версия: Расширение класса User и UserCreationForm
Начало » Django » Расширение класса User и UserCreationForm
1 2
lov3catch
Всем доброго времени суток, обращаюсь к вам за помощью.
Проблема такая: решил расширить юзера, добавил поле - nickname(поле выбрано в качестве тестового, суть в том, что бы просто научиться добавлять поля. какие - не важно):

#models.py
class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True, related_name='profile')
    nick_name = models.CharField(max_length=15)

Затем расширил UserCreationForm, что бы можно было вводить данные в новое поле при регистрации:
#views.py
class MyRegisterForm(UserCreationForm):
    print "OK!"
    nick_name = forms.CharField(max_length=30, required=True, widget=forms.TextInput)
    print "Ook"
    class Meta:
        model = UserProfile
    def save(self, commit=True):
        if not commit:
            raise NotImplementedError("Can't create User and UserProfile without database save")
        print "Saving..."
        user = super(MyRegisterForm, self).save(commit=False)
        user.nick_name = self.cleaned_data["nick_name"]
        user_profile = UserProfile(user=user, nick_name=self.cleaned_data['nick_name'])
        user_profile.save()
        print "Saving complete"
        return user, user_profile

Сама функция регистрации:
#views.py
def reg(request):
    if request.method =='POST':
        form = MyRegisterForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            print username
            password1 = form.cleaned_data['password1']
            print password1
            password2 = form.cleaned_data['password2']
            print password2
            nick_name = form.cleaned_data['nick_name']
            print nick_name
            form.clean_username()
            if password1 == password2:
                new_user = form.save()
                return render_to_response('registration/registration_complete.html')
            else:
                print "Password error"
                return render_to_response('registration/registration_fail.html')
        else:
            print "FORM error" #ТУТ ВАЛИТСЯ :(
            return render_to_response('registration/registration_fail.html')
    else:
        form = UserCreationForm() # An unbound form
    return render_to_response('registration/registration_new_user.html', {
        'form': form,
        },context_instance=RequestContext(request))

В настройки добавил:
#settings.py
AUTH_PROFILE_MODULE = 'registration.UserProfile'

Шаблон регистрации:
#registration_new_user.html
{% extends "base.html" %}
{% block content %}
  <h1>Регистрация пользователя</h1>
  <form action="registration" method="post">
    {% if form.error_dict %}
      <p class="error">Пожалуйста исправьте нижеприведённые ошибки.</p>
    {% endif %}
    {% if form.username.errors %}
      {{ form.username.html_error_list }}
    {% endif %}
    <label for="id_username">Логин:</label><br> {{ form.username }}<br>
    {% if form.password1.errors %}
      {{ form.password1.html_error_list }}
    {% endif %}
    <label for="id_password1">Пароль:</label><br> {{ form.password1 }}<br>
    {% if form.password2.errors %}
      {{ form.password2.html_error_list }}
    {% endif %}
    <label for="id_password2">Пароль (повторите):</label><br> {{ form.password2 }}<br>
    {% if form.nick_name.errors %}
      {{ form.nick_name.html_error_list }}
    {% endif %}
    <label for="id_nick_name">Пароль (повторите):</label><br> {{ form.nick_name }}<br>
      <br>
    <input type="submit" value="Зарегистрировать" />
  </form>
{% endblock %}

В итоге:
-при регистрации форма спотыкается на if form.is_valid()
-в шаблоне поле так же не отображается

Помогите советом, пожалуйста.
Заранее благодарен.
romankrv
lov3catch
Помогите советом, пожалуйста.
First of all , what is error do you get

lov3catch
#ТУТ ВАЛИТСЯ :(
We don't understand some words like: “ТУТ ” , could you please to submit more details about that error, if you'd like.

Thanks
lov3catch
romankrv
We don't understand some words like: “ТУТ ” , could you please to submit more details about that error, if you'd like.
Code crash in this plase.

if form.is_valid() = False
And I don`t understand where problem.

Thanks
romankrv
lov3catch
Code crash in this plase.
Please, give us a traceback from here, if you have it., because there are 90% that allows us to get solution for fix.

Thanks
lov3catch
No traceback, just redirect after:
if form.is_valid():
...
else:
   print "FORM error"
   return render_to_response('registration/registration_fail.html')
romankrv
Ok man, if you get some redirect than check your logic in there -
render_to_response - Is this function not work as you expect or what is going on there.
Maybe your form is not valid, please check it.

Luck for you.

lov3catch
Yes, form is not valid.
But I don`t now how I can fix it.
romankrv
Could you please to read django documentation about forms and how to deal with that. If you'd like because this is a first step is useful for you. Did you read about it early?

Luck
lov3catch
Reading…
thx you, if I search problem - I continue this topic.
lov3catch
I got the error

Exception at /registration
<ul class=“errorlist”><li>user<ul class=“errorlist”><li>This field is required.</li></ul></li></ul>

But, I don`t have a user field.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB