Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Class-Based Generic Views Register User

Good evening friends.

I'm trying to create an application for easy user registration. Using Django 1.5, my problem is the user is not saved in the database, my code here:

#forms.py
class UserCreationForm(forms.ModelForm):
    username = forms.RegexField(regex=r'^[\w.@+-]+$',max_length=30,label='Username')
    email = forms.EmailField(label="E-mail")
    password1 = forms.CharField(widget=forms.PasswordInput,label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput,label="Repeat Password")

    class Meta:
        models = User
        fields = ('username','email','password1','password2')

#views.py
from myapp.register.forms import UserCreationForm
class CreateUser(FormView):
     template_name = 'registration/registration_form.html'
     success:url = '/'
     form_class = UserCreationForm
    def is_valid(self, form):
        user = User.objects.create_user(form.cleaned_data['username'],
                                        form.cleaned_data['email'],
                                        form.cleaned_data['password1'])
        #user.save()
        return super(CreateUser, self).form_valid(form)

Everytime I try to create a user, they are not saved. What am I doing wrong?

"I am learning a little English, excuse my faults. Thanks"

like image 709
Andres Avatar asked Jun 17 '26 07:06

Andres


1 Answers

First, you do know that you have commented user.save(), do you? ;-)

That being said, you're approaching the whole issue in the wrong way. If you're trying to save a model instance, use CreateView as the base for your view rather than FormView. That way you won't need to write all that code you did, like the is_valid method (you also don't need to explicitly set the fields in your form; they will be extrapolated from your model's fields).

like image 151
Berislav Lopac Avatar answered Jun 20 '26 00:06

Berislav Lopac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!