开发者

I'm trying to save data from views

My forms.py file:

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)
开发者_如何学Go    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

My views.py file:

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),
        )

My register.html template:

<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>

The thing what it does in views.py is skip the try block and execute the except. What should I do or change?


So, You are saving the data twice. And in your model definition username must be unique. So, throwing integrity error. You are saving data in

1.) Forms save
2.) again same data you are saving in Views.

My suggestion.

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

In views.

Not resembles your code

All values are dummy here You just fit according to your values

register_name should be the instance of your Form

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()

Ok. I am writting here a create_user method:

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)


Since you are using ModelForm, I suggest you remove the 'except' in your registration function. It should look like this:

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),
        )

The reason of removing the 'except' is that you are already using modelform and it provides you with form validations. You don't have to create a template telling the user that their input is invalid (that is if you are using /validation/ to tell the user that they have invalid input).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜