0

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

1

1 Answer 1

-1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.