0

我需要你的帮助。我扩展了 User 类并添加了相同的字段,而不是扩展 UserCreationForm,但表单无效。if form.is_valid() 中的代码崩溃。请帮忙,为什么我的表格不正确?

模型.py

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

我的注册表

表格.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

注册功能

视图.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))

在设置中

设置.py

AUTH_PROFILE_MODULE = 'registration.UserProfile'

注册模板

registration_new_user.html

    {% extends "base.html" %}
{% block content %}
  <h1>Registration</h1>
  <form action="registration" method="post">
    {% if form.error_dict %}
      <p class="error">Please fix the error.</p>
    {% endif %}
    {% if form.username.errors %}
      {{ form.username.html_error_list }}
    {% endif %}
    <label for="id_username">Login:</label><br> {{ form.username }}<br>
    {% if form.password1.errors %}
      {{ form.password1.html_error_list }}
    {% endif %}
    <label for="id_password1">pass:</label><br> {{ form.password1 }}<br>
    {% if form.password2.errors %}
      {{ form.password2.html_error_list }}
    {% endif %}
    <label for="id_password2">pass(again):</label><br> {{ form.password2 }}<br>
    {% if form.nick_name.errors %}
      {{ form.nick_name.html_error_list }}
    {% endif %}
    <label for="id_nick_name">nick:</label><br> {{ form.nick_name }}<br>
      <br>
    <input type="submit" value="Reg" />
  </form>
{% endblock %}
4

1 回答 1

1

好吧,您的代码中有几个问题。例如,当请求为 a 时,您覆盖UserCreationFormMyRegistrationForm实例化后者POST,但当不是时,您将模板传递给 normal UserCreationForm

您确实有一个userUserCreationForm因为这是一个ModelForm模型,UserProfile并且您在那里定义了一个user字段。因此,当您使用POST.

我在这里看不到一个非常清晰的解决方案,因为您的代码有些棘手,但首先,使用相同的表单GETPOST请求类型,因此您的视图中的这一行

form = UserCreationForm() # An unbound form

会改变这个:

form = MyRegistrationForm() # An unbound form

在模板中它不会出现该字段user,因为您没有包含它们,但它在表单中。当您创建新用户时,该字段应设置为非必填,UserProfile因为您正在创建用户,因此不会有任何用户与 相关联。您可以将其设置为非必需,将参数添加blank=True到模型中:

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

更新:

这是您的基类UserCreationForm save方法的代码:

def save(self, commit=True):
    user = super(UserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

如您所见,此代码假定用户具有一个set_password属性,为了解决此问题,您必须向您的类添加一个def set_password(self, raw_password)方法。UserProfile发生此错误是因为表单基类被设计为与普通 DjangoUser类一起使用,您可能遇到的任何其他类似这样的错误,您可能会通过将所需的字段添加到您的UserProfile. 这个是这样解决的:

class UserProfile:
    ...
    def set_password(self, raw_password):
        # whatever logic you need to set the password for your user or maybe
        self.user.set_password(raw_password)
    ...

我希望这能给问题带来一些启示。祝你好运!

于 2013-05-20T12:50:12.223 回答