【django】社内SNSアプリを作ってみる⑥(ListView2 modelとの連携とか)【pythonメモ】

pythonLOGO

まずはviews.pyから

models.pyで定義したBoardModelをviews.pyに埋め込んでいく

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
from .models import BoardModel

# Create your views here.

def signupfunc(request):
  if request.method =='POST':
    username2 = request.POST['username']
    password2 = request.POST['password']
    try:
      User.objects.get(username=username2)
      return render(request, 'signup.html', {'error':'このユーザーは登録されています'})
    except:
      user = User.objects.create_user(username, '', password2)
      return render(request, 'signup.html', {'some':100})
  return render(request, 'signup.html', {'some':100})

def loginfunc(request):
  if request.method =='POST':
    username2 = request.POST['username']
    password2 = request.POST['password']
    user = authenticate(request, username=username2, password=password2)
    if user is not None:
      login(request, user)
      return redirect('signup')
    else:
      return redirect('login')
  return render(request, 'login.html')

def listfunc(request):
  object_list = BoardModel.objects.all()
  return render(request, 'list.html', {'object_list':object_list})

list.htmlの中で表示させる

{% extends 'base.html' %}

{% block customecss %}
{% endblock customecss %}

{% block header %}
<div class="alert alert-primary" role="alert">
  社内SNS
</div>
{% endblock header %}

{% block content %}
<div class='container'>
  {% for item in object_list %} #forで投稿内容を全部表示させる
  <div class="alert alert-success" role="alert">
    <p>タイトル:{{item.title}}</p> #model.pyで定義したものを追加
    <p>投稿者:{{item.auther}}</p> #model.pyで定義したものを追加
    <a href="#" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">Primary link</a>
    <a href="#" class="btn btn-secondary btn-lg active" role="button" aria-pressed="true">Link</a>
  </div>
  {% endfor %}
</div>
{% endblock content %}

タイトルと投稿者が表示されるようになった

ログイン状態を判定する機能の実装

公式サイトからlogin_required デコレータを確認する

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect
from .models import BoardModel
from django.contrib.auth.decorators import login_required #追記

# Create your views here.

def signupfunc(request):
  if request.method =='POST':
    username2 = request.POST['username']
    password2 = request.POST['password']
    try:
      User.objects.get(username=username2)
      return render(request, 'signup.html', {'error':'このユーザーは登録されています'})
    except:
      user = User.objects.create_user(username, '', password2)
      return render(request, 'signup.html', {'some':100})
  return render(request, 'signup.html', {'some':100})

def loginfunc(request):
  if request.method =='POST':
    username2 = request.POST['username']
    password2 = request.POST['password']
    user = authenticate(request, username=username2, password=password2)
    if user is not None:
      login(request, user)
      return redirect('list') # 間違ってたので修正
    else:
      return redirect('login')
  return render(request, 'login.html')

@login_required #追記
def listfunc(request):
  object_list = BoardModel.objects.all()
  return render(request, 'list.html', {'object_list':object_list})
"""
Django settings for boardproject project.

Generated by 'django-admin startproject' using Django 3.0.8.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'k&tz9=)tob9a8f(_oh492q1817)*pz8lk4dw7e*-hkw15*&vwg'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'boardapp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'boardproject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR, 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'boardproject.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/medi/'

LOGIN_URL = 'login' #追記

ログアウト機能の実装

さきほどと同じ公式ページの内容から

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout # logoutを追記
from django.shortcuts import redirect
from .models import BoardModel
from django.contrib.auth.decorators import login_required

# Create your views here.

def signupfunc(request):
  if request.method =='POST':
    username2 = request.POST['username']
    password2 = request.POST['password']
    try:
      User.objects.get(username=username2)
      return render(request, 'signup.html', {'error':'このユーザーは登録されています'})
    except:
      user = User.objects.create_user(username, '', password2)
      return render(request, 'signup.html', {'some':100})
  return render(request, 'signup.html', {'some':100})

def loginfunc(request):
  if request.method =='POST':
    username2 = request.POST['username']
    password2 = request.POST['password']
    user = authenticate(request, username=username2, password=password2)
    if user is not None:
      login(request, user)
      return redirect('list')
    else:
      return redirect('login')
  return render(request, 'login.html')

@login_required
def listfunc(request):
  object_list = BoardModel.objects.all()
  return render(request, 'list.html', {'object_list':object_list})

# 下3行も追記
def logoutfunc(request):
    logout(request)
    return redirect('login')
from django.urls import path
from .views import signupfunc, loginfunc, listfunc, logoutfunc

urlpatterns = [
    path('signup/', signupfunc, name='signup'),
    path('login/', loginfunc, name='login'),
    path('list/', listfunc, name='list'),
    path('logout/', logoutfunc, name='logout'),
]
{% extends 'base.html' %}

{% block customecss %}
{% endblock customecss %}

{% block header %}
<div class="alert alert-primary" role="alert">
  社内SNS
</div>
{% endblock header %}

{% block content %}
<div class='container'>
  {% for item in object_list %}
  <div class="alert alert-success" role="alert">
    <p>タイトル:{{item.title}}</p>
    <p>投稿者:{{item.auther}}</p>
    <a href="#" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">Primary link</a>
    <a href="#" class="btn btn-secondary btn-lg active" role="button" aria-pressed="true">Link</a>
  </div>
  {% endfor %}
  <a href="{% url 'logout '%}">ログアウト</a>
</div>
{% endblock content %}

んーまだ先長いね。



 

あ、宜しければ・・・。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です