简体   繁体   中英

how to use user authentication in django

i have a html template which i want to use for authentication in django. I am using pymongo to connect to remote mongodb and fetch_data. The remote mongodb has a collection which has username & password for a demo user. I read that django has a inbuilt authentication module but i dont want to use that.

My template :

<form action="/index.html">
    <div class="form-group">
        <div class="input-group">
            <div class="input-group-addon"><i class="fa fa-user"></i></div>
            <input type="text" class="form-control" placeholder="Username">
        </div>
    </div>
    <div class="form-group">
        <div class="input-group">
            <div class="input-group-addon"><i class="fa fa-asterisk"></i></div>
            <input type="password" class="form-control" placeholder="Password">
        </div>
    </div>
    <div class="row">
        <div class="col-xs-8 text-left checkbox">
            <label class="form-checkbox form-icon">
            <input type="checkbox"> Remember me
            </label>
        </div>
        <div class="col-xs-4">
            <div class="form-group text-right">
            <button class="btn btn-success text-uppercase" type="submit">Sign In</button>
            </div>
        </div>
    </div>
</form>

How can i pass data from my template to my views.py file? Currently I am not using any authentication.

my views.py:

from django.shortcuts import render
from django.http import HttpResponse

def login(request):
    return render(request, 'login/login.html')

In Pymongo, I can use command db.getCollection('users').find({'email':'%s'}) {{email}} to pass email and verify.

PS: Most tutorial i read were about django's inbuilt authentication.

The generic way is to write custom authentication backend which handles authentication for you. Then it is recommended to create custom form which is rendered in your template.

Authentication backend

class YourBackend(object):
    def authenticate(self, username=None, password=None):
        # Check the username/password and return a User.

    def get_user(self, user_id):
        # return user by given user_id

Settings

When you have implemented your own authentication backend you should define it inside django settings.py. The first one is django's default authentication backend.

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'your.own.authentication.backed',
)

Form

from django import forms

class YourLoginForm(forms.Form):
   username = forms.CharField(max_length=254)
   password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)

View

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth import authenticate, get_backends

def login(request):
    form = YourLoginForm(request.POST or None)

    if form.method == 'POST':
       if form.is_valid():
           user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])

           if user:
               # redirect user to somewhere

    return render(request, 'login/login.html')

Template

<form action="{% url 'your-login' %}" method="POST">
    {{ form.non_field_errors }}
    <div class="form-group">
        <div class="input-group">
            {{ form.username.errors }}
            <div class="input-group-addon"><i class="fa fa-user"></i></div>
            {{ form.username }}
        </div>
    </div>
    <div class="form-group">
        <div class="input-group">
            {{ form.username.errors }}
            <div class="input-group-addon"><i class="fa fa-asterisk"></i></div>
            {{ form.password }}
        </div>
    </div>
    <div class="row">
        <div class="col-xs-4">
            <div class="form-group text-right">
            <button class="btn btn-success text-uppercase" type="submit">Sign In</button>
            </div>
        </div>
    </div>
</form>

Urls

url(r'^login$', 'views.login', name='your-login'),

I suggest you to use external libraries for authentication and profiling. As I remember they have got options for mongodb. But if you want to reinvent the wheel, then you should use following.

1) Create class that extends form.ModelForm to handle registration and authentication process. You could read documentation how to do it. If will help you to handle validation of the data. You'll able to validate unique email fields and other stuff.

2) Create HTML form. You could use existing and just connect it with your ModelClass.

3) If you're using forms you could get data just with following command in yor controller:

form = MyForm(request.POST or None)

Then you'll be able to pass data to this form. If you don't want to use and form classes then you could retrieve if in such way in your controller:

if request.method == 'POST':
    login = request.POST.get('login', None)
    password = request.POST.get('password', None)

Assign controller with the form you could using urls.py, just the same way:

url(r'^login$', 'views.login', name='login'),

So using forms class you'll be able to pass empty form when GET request arrived and if it's POST request then you could collect data. Also, add to your HTML form following:

<form action="/login" method="post">

4) When you receive data from your login form you should authenticate. This could be done using custom authentication backend. You could find info here or just Google how to do it. I've never done it before, but it's pretty simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM