from django import forms from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm class PhoneLoginForm(forms.Form): phone = forms.CharField( label="Phone", max_length=255, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter phone number', 'autofocus': True }) ) password = forms.CharField( label="Password", widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter password' }) ) def clean(self): cleaned_data = super().clean() phone = cleaned_data.get("phone") password = cleaned_data.get("password") if phone and password: from django.contrib.auth import get_user_model User = get_user_model() user = authenticate(username=phone, password=password) if user is None: raise forms.ValidationError("Invalid phone number or password") self.user = user return cleaned_data def get_user(self): return getattr(self, 'user', None)