[컴][웹] Django 에서 로그인 페이지 만들기

장고에서 로그인 페이지 만들기



Django 에서 Login page 만들기


default login/logout page

기본적으로 아래처럼 login page 가 제공된다. 기본적으로 url을 변경하지 않으면

  • accounts/login

으로 들어가면 된다.

하지만 url 을 바꾸고 싶다면 아래처럼 하면 된다.

from django.contrib.auth.views import login, logout


urlpatterns = [
    
    url(r'^login/$', login,
       {'template_name': 'login.htm'}, name='login'),
       
    url(r'^logout/$', logout, name='logout')
]

이 때 LoginRequiredMixin 등을 사용하면, login 이 안된 경우에 login 화면으로 이동하는데, 이 때 사용되는 url 은 기본적으로 accounts/login 이다. 그런데 이것을 변경하고 싶다면 settings.py 에 LOGIN_URL 변수를 바꿔주면 된다.
# settings.py
from django.core.urlresolvers import reverse_lazy
LOGIN_URL = reverse_lazy('acc:login')


login.htm

<html> 
 <head>
  <title>Login</title>
 </head>
 <body>
  <h2>Login</h2>
   <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Login</button>
   </form>
 </body>
</html>



login page 만들기

settings.py


MIDDLEWARE_CLASSES = (
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
)

INSTALLED_APPS=(
    'django.contrib.auth',
    'django.contrib.contenttypes',
    ...
)


urls.py

from myapp.views import loginUser

urlpatterns = [
    url(r'^login/$', loginUser, name='login'),

]


views.py

template folder 에 login.html 을 넣어놓자.

from django.http import *
from django.shortcuts import render_to_response,redirect
from django.template import RequestContext
from birthdayreminder.models import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout

def loginUser(request):
    logout(request)
    username = password = ''
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/main/')
    return render_to_response('login.html', context=RequestContext(request))

@login_required(login_url='/login/')
def main(request):
  ...




Class version[ref. 3]


from django.utils.http import is_safe_url
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView, RedirectView
class LoginView(FormView): """ Provides the ability to login as a user with a username and password """ success_url = '/auth/home/' form_class = AuthenticationForm redirect_field_name = REDIRECT_FIELD_NAME template_name = 'login.htm' # /templates/login.htm @method_decorator(sensitive_post_parameters('password')) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): # Sets a test cookie to make sure the user has cookies enabled request.session.set_test_cookie() return super(LoginView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): auth_login(self.request, form.get_user()) # If the test cookie worked, go ahead and # delete it since its no longer needed if self.request.session.test_cookie_worked(): self.request.session.delete_test_cookie() return super(LoginView, self).form_valid(form) def get_success_url(self): redirect_to = self.request.REQUEST.get(self.redirect_field_name) if not is_safe_url(url=redirect_to, host=self.request.get_host()): redirect_to = self.success_url return redirect_to



Ajax 용 login page

client 에서 login button 을 누를 때 login-action 을 호출해서 login 동작을 하게 한다. 아래는 login-action 에 대한 code 이다. 참고로 DjangoRestFramework 를 사용했다.


아래 소스를 참고하자.



Reference

  1. Django - How do I create a custom login page ?
  2. Chapter 14: Sessions, Users, and Registration > Logging In and Out
  3. Django Auth Class-Based-Views Login and Logout (Example)



댓글 없음:

댓글 쓰기