doyoubi
doyoubi

Reputation: 153

Django: Is it a correct way to override form field of AuthenticationForm?

I find it's convenient to use AuthenticationForm of Django But since the username of our client is a little bit long to remember, and the amount of our client is not much, we want to use select widget in the login page. So I use the following code to achieve it. It works.

from django.contrib.auth.forms import AuthenticationForm

class SignInForm(AuthenticationForm):
    username = forms.ModelChoiceField(queryset=User.objects.all())

in the views.py:

def post(self, request):
    form = SignInForm(data=request.POST)
    if form.is_valid():
        login(request, form.get_user())
        return HttpResponseRedirect(reverse('account:signin'))
    return render(request, 'account/sign-in.html', {'form': form})

However, I can't find any similar usage in documentation. So I'm not sure whether it's correct to do that.

I don't know whether it's similar to ModelForm: https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets

I want to know what happen here. Does the username I declare in SignInForm prevent AuthenticationForm from generating its username like ModelForm? But the AuthenticationForm successfully treat the username I declare just like the username it should have generate?

Upvotes: 2

Views: 556

Answers (1)

Jiangge Zhang
Jiangge Zhang

Reputation: 4704

It looks good.

The source of AuthenticationForm defined username and password field. Your subclass overrided the username field as normal.

All the form fields are actually implementations of the Python descriptor protocol. They are only general class members there.

Upvotes: 2

Related Questions