【django】社内SNSアプリを作ってみる⑧(既読機能の実装、CreateViewの作成)【pythonメモ】

pythonLOGO
記事内にプロモーションを含むことがあります

当サイトの記事内では、アフィリエイト広告を掲載している場合があります。



既読機能の実装

detail.html

{% extends 'base.html' %}

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

{% block header %}
<div class="alert alert-primary" role="alert">
個別投稿
</div>
{% endblock header %}

{% block content %}
<div class='container'>

  <div class="alert alert-success" role="alert">
    <p>タイトル:{{object.title}}</p>
    <p>投稿者:{{object.auther}}</p>
    <p>内容:{{object.content}}</p>
    <p><img src="{{object.images.url}}" width=300></p>

    <a href="{% url 'good' object.pk %}" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">いいねする</a>
    <a href="{% url 'good' object.pk %}" class="btn btn-secondary btn-lg active" role="button" aria-pressed="true">既読にする</a>
  </div>


</div>
{% endblock content %}

urls.py

from django.urls import path
from .views import signupfunc, loginfunc, listfunc, logoutfunc, detailfunc, goodfunc, readfunc

urlpatterns = [
    path('signup/', signupfunc, name='signup'),
    path('login/', loginfunc, name='login'),
    path('list/', listfunc, name='list'),
    path('logout/', logoutfunc, name='logout'),
    path('detail/<int:pk>', detailfunc, name="detail"),
    path('good/<int:pk>', goodfunc, name='good'),
    path('read/<int:pk>', readfunc, name='read'),
]

views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, 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})

def logoutfunc(request):
    logout(request)
    return redirect('login')

def detailfunc(request, pk):
  object = BoardModel.objects.get(pk=pk)
  return render(request, 'detail.html', {'object':object})

def goodfunc(request, pk):
  post = BoardModel.objects.get(pk=pk)
  post.good = post.good + 1
  post.save()
  return redirect('list')

def readfunc(request, pk):
  post = BoardModel.objects.get(pk=pk)
  post2 =request.user.get_username()
  if post2 in post.readtext:
    return redirect('list')
  else:
    post.read += 1
    post.readtext = post.readtext + ' ' + post2
    post.save()
    return redirect('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 %}
  <div class="alert alert-success" role="alert">
    <p>タイトル:<a href="{% url 'detail' item.pk %}">{{item.title}}</a></p>
    <p>投稿者:{{item.auther}}</p>
    <a href="#" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">いいね:{{item.good}}</a>
    <a href="#" class="btn btn-secondary btn-lg active" role="button" aria-pressed="true">既読:{{item.read}}人</a>
  </div>
  {% endfor %}
  <a href="{% url 'logout' %}">ログアウト</a>
</div>
{% endblock content %}

こんな感じ

CreateViewの作成

まずはtemplates内でcreate.htmlを作成する

urlのつなぎこみ

from django.urls import path
from .views import signupfunc, loginfunc, listfunc, logoutfunc, detailfunc, goodfunc, readfunc, BoardCreate

urlpatterns = [
    path('signup/', signupfunc, name='signup'),
    path('login/', loginfunc, name='login'),
    path('list/', listfunc, name='list'),
    path('logout/', logoutfunc, name='logout'),
    path('detail/<int:pk>', detailfunc, name="detail"),
    path('good/<int:pk>', goodfunc, name='good'),
    path('read/<int:pk>', readfunc, name='read'),
    path('create/', BoardCreate.as_view(), name='create'),
]
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect
from .models import BoardModel
from django.contrib.auth.decorators import login_required
from django.views.generic import CreateView
from django.urls import reverse_lazy

# 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})

def logoutfunc(request):
    logout(request)
    return redirect('login')

def detailfunc(request, pk):
  object = BoardModel.objects.get(pk=pk)
  return render(request, 'detail.html', {'object':object})

def goodfunc(request, pk):
  post = BoardModel.objects.get(pk=pk)
  post.good = post.good + 1
  post.save()
  return redirect('list')

def readfunc(request, pk):
  post = BoardModel.objects.get(pk=pk)
  post2 =request.user.get_username()
  if post2 in post.readtext:
    return redirect('list')
  else:
    post.read += 1
    post.readtext = post.readtext + ' ' + post2
    post.save()
    return redirect('list')

class BoardCreate(CreateView):
  template_name = 'create.html'
  model = BoardModel
  fields = ('title', 'content', 'author', 'images')
  success_url = reverse_lazy('list')
{% extends 'base.html'%}

{% block content %}

<form action ='' method='POST' enctype="multipart/form-data">{% csrf_token %}

<p>タイトル:<input type='text' name='title'></p>
<p>内容:<input type='text' name='content'></p>
<p>画像:<input type='file' name='images'></p>
<input type='hidden' name='author' value='({ user.username })'>

<input type='submit' value='作成する'>
</form>

{% endblock content %}
from django.db import models

# Create your models here.

class BoardModel(models.Model):
  title = models.CharField(max_length=100)
  content = models.TextField()
  author = models.CharField(max_length=100)
  images = models.ImageField(upload_to='')
  good = models.IntegerField(null=True, blank=True, default=0)
  read = models.IntegerField(null=True, blank=True, default=0)
  readtext = models.CharField(max_length=200, null=True, blank=True, default='a')

models.pyの中身を変えたので、一度makemigrationsが必要になる

{% extends 'base.html'%}

{% block content %}

{% if user.is_authenticated %}
<form action ='' method='POST' enctype="multipart/form-data">{% csrf_token %}

<p>タイトル:<input type='text' name='title'></p>
<p>内容:<input type='text' name='content'></p>
<p>画像:<input type='file' name='images'></p>
<input type='hidden' name='author' value='({ user.username })'>

<input type='submit' value='作成する'>
</form>
{% else %}
ログインしてください
{% endif %}
{% endblock content %}

ログインしていない場合は、ログインしてくださいというメッセージが出るようにした。





記事内にプロモーションを含むことがあります

当サイトの記事内では、アフィリエイト広告を掲載している場合があります。

あ、宜しければ・・・。

2 件のコメント

  • コメントを残す

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