How to access djagno built in login system fields

282 views Asked by At

So when I look on tutorials online on how to use the django built in login system I found that they use {{ form.as_p }} in templates, how can I access each field individualy in tmeplates so I can put them in my own styled template ?

2

There are 2 answers

6
Fedor Soldatkin On BEST ANSWER

You can redefine fields by inheriting default AuthenticationForm

from django import forms
from django.contrib.auth.forms import AuthenticationForm


class UserLoginForm(AuthenticationForm):
    def __init__(self, *args, **kwargs):
        super(UserLoginForm, self).__init__(*args, **kwargs)

    username = forms.EmailField(widget=forms.TextInput(
        attrs={
             'class': 'your-class',
             'placeholder': 'Enter your username',
             'id': 'username-input'
        }))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class': 'your-class'}))

In templates you can access these fileds as {{ form.username }} and {{ form.password }}

Also you can wrap each field in <div> tag and add some classes, for example:

<form action="/your-view/" method="post">
    {% csrf_token %}
    <div id="username-input" class="form-control your-class">
        {{ form.username }}
    </div>
    <div id="password-input" class="another-class">
        {{ form.password }}
    </div>
    <input type="submit" value="OK">
</form>
0
edgars On

You can lookup login form field names from Django source code. Here - https://github.com/django/django/blob/master/django/contrib/auth/forms.py.