0
votes

I wrote two views as the class in Django in order to do the Registration and Login for my website. But the problem is that the user objects get created successfully. But when I try to authenticate later getting the warning message showing that user with that username already exists in Django The two views are given below

class RegistrationView(View):
    form_class=RegistrationForm
    template_name='eapp/user_registration_form.html'


    def get(self,request):
        form=self.form_class(None)
        return render(request,self.template_name,{'form':form})

    def post(self,request):
        form=self.form_class(request.POST)

        if form.is_valid():

            user=form.save(commit=False)

            #cleaned (normalized) data
            username =form.cleaned_data['username']
            password =form.cleaned_data['password']
            email=form.cleaned_data['email']

            user.set_password(password)
            user.save()

        return render(request,self.template_name,{'form':form,})


class LoginView(View):
    form_class=LoginForm
    template_name='eapp/user_login_form.html'


    def get(self,request):
        form=self.form_class(None)
        return render(request,self.template_name,{'form':form})

    def post(self,request):
        form=self.form_class(request.POST)

        if form.is_valid():


            #cleaned (normalized) data
            username =form.cleaned_data['username']
            password =form.cleaned_data['password']



            #authenticatin

            user=authenticate(username=username,password=password)

            if user is not None:
                if user.is_active:
                        login(request,user)
                        return render(request,'eapp/index.html',{})

        return render(request,self.template_name,{'form':form,})

here is my forms.py' from django.contrib.auth.models import User from django import forms

class RegistrationForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model=User
        fields=['username','email','password']

class LoginForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model=User
        fields=['username','password'

]

How can I solve this? ThankYou

1
Are you can share yours forms.py?Brian Ocampo
@BrianOcampo one second broSelf
@BrianOcampo updatedSelf
@Darshan where?Self
Forget my last comment, Can u please check whether login view is getting invoked on click of login button ????Darshan

1 Answers

4
votes

Change your LoginForm for a Form without model:

from django import forms

class LoginForm(forms.Form):

    username = forms.CharField(label = 'Nombre de usuario')
    password = forms.CharField(label = 'Contraseña', widget = forms.PasswordInput)

This way your form will validate that the fields are entered and will not take validations from the User model