我正在尝试从视图中保存数据

时间:2011-09-07 07:55:51

标签: django

我的forms.py文件:

class RegisterForm(ModelForm):
    """This form lets people register as members."""

    help_string = "Please choose a password that is at 6 characters long,"\
        "and contains at least on speacial character or number"

    First_Name = forms.CharField(max_length=50)
    Last_Name = forms.CharField(max_length=50)  
    Username = forms.CharField(max_length=50)
    Password = forms.CharField(max_length=50)
    Confirm_Password = forms.CharField(max_length=50)
    Email_Address = forms.EmailField()
    Address = forms.CharField(widget=forms.Textarea)

    def save(self, commit=True): 
        cd = self.cleaned_data
        u = User.objects.create_user(
            username=self.cleaned_data['Username'],
            email=self.cleaned_data['Email_Address'],
            password=self.cleaned_data['Password'],
            )
        u.is_staff = True
        u.save()
        u.First_Name = self.cleaned_data['First_Name']
        u.Last_Name = self.cleaned_data['Last_Name']
        m = self.instance
        m.user = u
        if not commit:
            return [m, u]
        u.save()
        m.save()
        return m

我的views.py文件:

def register(request):
    if request.method == "POST":
    form = RegisterForm(request.POST)
        if form.is_valid():
            try:
                instance = form.save()
                return HttpResponseRedirect('/registered/')
            except:
                return HttpResponseRedirect('/validation/')
    else:
        form = RegisterForm()

    return render_to_response(
        'homepage/register.html',     
        {'form':form,},
        context_instance=RequestContext(request),
        )

我的register.html模板:

<h4>Register</h4>
<form action="" method="POST">
    <table border="0" cellpadding="1" cellspacing="1" id="eric">
        <tr>
        <td>{{ form.as_table }}</td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" value="Create Account">
                <input type="Reset"  value="Clear"></td>
        </tr>
    </table>
</form>

它在views.py中的作用是跳过try块并执行except。 我该怎么做或改变?

2 个答案:

答案 0 :(得分:0)

所以,您要保存两次数据。在您的模型定义中,用户名必须是唯一的。所以,抛出完整性错误。您正在

中保存数据
1.) Forms save
2.) again same data you are saving in Views.

我的建议。

clean your data in the forms.
Remove save() from forms.
save form in views.


class RegisterForm(ModelForm):
        """This form lets people register as members."""

        help_string = "Please choose a password that is at 6 characters long,"\
            "and contains at least on speacial character or number"

        First_Name = forms.CharField(max_length=50)
        Last_Name = forms.CharField(max_length=50)  
        Username = forms.CharField(max_length=50)
        Password = forms.CharField(max_length=50)
        Confirm_Password = forms.CharField(max_length=50)
        Email_Address = forms.EmailField()
        Address = forms.CharField(widget=forms.Textarea)

        def clean_name(self,):
            username = self.cleaned_data['Username']
            return username

        def clean_email(self,):
            email = self.cleaned_data['Email_Address']
            param = {'email': email}
            if dbapi.get_user(**param):
                raise ValidationError('Email already registered')
            return email
        def clean_password(self,):
            // your logic here

在观点中。

与您的代码不相似

此处所有值均为虚拟您只需根据您的值进行调整

register_name应该是表单的实例

username = register_form.cleaned_data['username']
email = register_form.cleaned_data['email']
password = register_form.cleaned_data['password']
name = register_form.cleaned_data['name']
# Create a user obj                                                                                                                             
user_obj = create_user(username, email, password) // to create a user_obj
# https://docs.djangoproject.com/en/dev/topics/auth/#creating-users
user_obj.first_name = 'xxxxxxxxx'
user_obj.last_name = 'xxxxxxxxxx'
user_obj.save()

确定。我在这里写create_user方法:

from django.contrib.auth.models import User
def create_user(username, email, password):
    # This will return the user_obj
    return User.objects.create_user(username, email, password)

答案 1 :(得分:0)

由于您使用的是ModelForm,我建议您删除注册功能中的“除外”。它应该是这样的:

def register(request):
    if request.method == "POST":
    form = RegisterForm(request.POST)
        if form.is_valid():
            instance = form.save()
            return HttpResponseRedirect('/registered/')

    else:
        form = RegisterForm()

    return render_to_response(
        'homepage/register.html',     
        {'form':form,},
        context_instance=RequestContext(request),
        )

删除'except'的原因是您已经在使用modelform并且它为您提供表单验证。您不必创建模板告诉用户他们的输入无效(即如果您使用/ validation /告诉用户他们输入无效)。