简体   繁体   中英

user with that username already exists in Django

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM