Issue
I tried to do this to remove username validation
def clean_username(self):
return "valid_username"
But the is_valid()
method is showing false. Even when i give the correct username and password
I also tried this
def clean_username(self):
return self.cleaned_data.get('username')
views.py
def login(request):
if request.method == 'POST':
form = LoginUser(request=request.POST, data=request.POST)
if form.is_valid():
print(True)
print(form.cleaned_data['username'])
print(form.cleaned_data['password'])
print(form.is_valid())
else: form = LoginUser()
context ={
'form': form,
}
return render(request, 'login.html', context)
forms.py
class LoginUser(AuthenticationForm):
username = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'class': form_class, 'placeholder': 'username', }))
password = forms.CharField(min_length=8, required=True, widget=forms.PasswordInput(attrs={'class': form_class, 'placeholder': 'password', }))
def clean_username(self):
return "valid_username"
I think I need to change the is_valid
method
Solution
This modification removes the 'username' error from the form errors before calling the parent is_valid
method. It effectively bypasses the validation for the username, allowing you to handle it in your custom way in the clean_username
method.
from django.contrib.auth.forms import AuthenticationForm
from django import forms
class LoginUser(AuthenticationForm):
username = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'class': 'form_class', 'placeholder': 'username'}))
password = forms.CharField(min_length=8, required=True, widget=forms.PasswordInput(attrs={'class': 'form_class', 'placeholder': 'password'}))
def clean_username(self):
return "valid_username"
def is_valid(self):
# Skip the default validation for username
self.errors.pop('username', None)
return super().is_valid()
Answered By - Pruthvi prajapati
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.