Django | Codecademy | Accounts and Authentication


Admin Account


In order to access the Admin interface, we must create a superuser
  • superuser has the permissions to freely control data
  • python3 manage.py createsuperuser
  • shell will prompt us to type in a username, email, and password
  • once completed, we can navigate to the /admin route and log in with the credentials we just used to create our superuser
  • If we get redirected to the index page, that means our login was successful
  • Registering Tables in Admin


    In order to interact with a database table through the admin interface, we first need to register the model.
    1. Registering and configuring a model is done by adding the models into the app’s admin.py file
    # myapp_root/book_catalog/admin.py
     
    from .models import Book
     
    admin.site.register(Book)
  • then use the register() method to register our models
  • admin.site.register(Book)
  • we will be directed to a table that shows us all the information and records held in this database table
  • User Objects

  • Import User Object from Django's systemfrom django.contrib.auth.models import User
  • Use method to create users.create_user()
  • user = User.objects.create_user(username="myusername", email="[email protected]", password="mypassword")
  • automatically creates and saves the user to the database
  • hashes the password - not a plain string anymore, so security ↑
  • can call the .save() method in order to save the user object back to the database if we make any further changes.
  • user = User.objects.create_user(username="myusername", email="[email protected]", password="mypassword")
    **終了shellCtrl+Dorexit()

    Authenticating Users


    ViewFunctionにユーザ認証ロジックを追加し、authenticate()functionを実行します.
  • user = authenticate(request, username=username, password=password)
  • この関数は、認証情報(ユーザー名、パスワード)をパラメータとして受け入れます.
  • credentialがサーバデータと一致する場合、User objectが返されます.
  • django.shortcutsredirect()では、name of a viewを入力することで、ユーザーを特定のビューにリダイレクトできます.
  • 正しくない場合は、PermissionDenied exception,Noneが返されます.
  • request.POSTフォーマットで入力されたデータを解析
  • if/else異常処理
  • from django.contrib.auth import authenticate
     
    def login_view(request):
      # Both username and password are captured from the submitted log in form
      username = request.POST["username"]
      password = request.POST["password"]
     
      # Both username and password are passed into the authenticate() method to verify the user
      user = authenticate(request, username=username, password=password)
     
      # If the user is valid, then a user object is returned.
      if user is not None:
        # Log in user and redirect them
        return redirect("home.html")
      else:
        return HttpResponse("Invalid credentials!")

    Log In


    user objectが作成されている場合は、その認証情報を使用してサイトにログインできます.
    Djangoが提供するlogin()関数を使用すればいいです.
    # views.py
    From django.contrib.auth import login
     
    def login_view(request):
      # ... Other code
      login(request, user)
  • django.contrib.authimport
  • login()関数は、2つのrequestuserを受け入れます.
  • ログインに成功すると、セッションが作成されます.
  • セッションとは?
    ユーザーのログインとログアウトの時間.
  • sessionは特殊なクッキーを使用します.Cookieは、ブラウザの情報を表示し、サイトを閲覧するたびにログインしないようにログイン情報を保持するセッションidを指定します.
  • from django.contrib.auth import authenticate, login
    from django.shortcuts import redirect
     
    def login_view(request):
      username = request.POST["username"]
      password = request.POST["password"]
     
      user =  authenticate(request, username=username, password=password)
     
      # Check if a user is verified and authenticated
      if user is not None:
        # Use the returned user object in login()
        login(request, user)
     
        # Redirect to home page after logging in
        return redirect("home.html")
      else:
        render(request, "registration/login.html", context)
    現在、私たちのifstatementでは、
    (request+作成したuserobjectを含む)
    セッションはlogin()で作成できます.
    # Other login_view code...
      if user is not None:
        login(request, user)
        return redirect("dashboard.html")
      else:
        render(request, "registration/login.html", context)

    Login Mixin and Decorator


    Login Mixin

  • mixins = a type of class that is used to “mix in” extra properties and methods into another class.
  • import LoginRequiredMixin from django mixins
    # views.py
    from django.contrib.auth.mixins import LoginRequiredMixin
    Mixins can be passed as argument
    We want to add login mixin before view ( left: mixin, right: view )
    # views.py
    class SomeView(LoginRequiredMixin, ListView):
      model = ModelExample

    Decorators

    # views.py
    from django.contrib.auth.decorators import login_required
     
    @login_required
    def profile(request):
      return render(request, "app/profile.html", name="profile")
    Decoratorを使用すると、ログインしていないユーザーを拒否できます.
  • With just one line, Django is able to take care of all the logic required to deny/allow access to specific pages!
  • Both the login mixin and decorator do roughly the same thing. The main difference lies in the syntax and implementation — mixins are used for classes, while decorators are used for functions.

    Log-out

  • logout() function takes in a request and returns None :
  • # views.py
    
    from django.contrib.auth import logout
     
    def logout_view(request):
      # ... Other logic
      logout(request)
      return redirect("home")
  • By calling the logout() function we completely delete the session data that was associated with the logged in user.
  • It is important to note that calling thelogout() function doesn’t throw any errors if the user is not logged in. Once the logout function is called, we can then redirect the user to a different view page by using redirect() .
  • access the logout view within our home page :
    add a new path to logout our users in our app’s urls.py:
  • urlpatterns = [
      path("/logout", logout, name="logout")
    ]
    このルートディレクトリは、セッションの終了後にログアウトされます.

    Login Template

    <!-- registration/login.html -->
     
    {% block title %}Login{% endblock %}
     
    {% block content %}
      <h2>Login</h2>
        <form method="post">
          {% csrf_token %}
          <table>
            {{ form.as_p }}
            <tr>
              <td>&nbsp;</td>
              <td><input type="submit" value="Submit"></td>
            </tr>                
          </table>
        </form>
    {% endblock %}

    Signup Template and View

    UserCreationForm&CreateViewclass-based viewの使用
    # views.py
    from django.contrib.auth.forms import UserCreationForm
    from django.urls import reverse_lazy
     
    class SignUp(CreateView):
      form_class = UserCreationForm
      success_url = reverse_lazy("login")
      template_name = "registration/signup.html"
    Our SignUp class is using a CreateView class, in which we can specify what information to include.
  • The first thing we’ll set is the form_class as a UserCreationForm which will generate the necessary fields for us (username and password).
  • The UserCreationForm was imported from django.contrib.auth.forms
  • Afterward, we use the success_url attribute to assign a URL to redirect the signed up user
  • We use the reverse_lazy() method to generate a full URL from a name.
  • We set the successful redirect to go to "login" path since we still want a user to login.
  • Lastly, we’ll assign "registration/signup.html" to template_name so we can render that specific template.
  • urls.pyで作成したビュー.pyの追加
    # urls.py
     
    path("signup/", views.SignUp.as_view(), name="signup"),