[Django]Pinterestの作成(6)


MagicGridの概要とArticlippの入門


MagicGridは、カードレイアウトを提供するライブラリです.この授業ではこのライブラリを使います.
次のリンクのハブアドレスに入ると、使い方や説明が確認できます.
https://github.com/e-oj/Magic-grid
まずはarticleappを作ります.
python manage.py startapp articleapp
settings.pyにarticleappとurlsを追加します.pyはurlも追加します.次に、articleapp内のurlsを下図のように示します.pyを作成し、コードを記述します.
from django.urls import path
from django.views.generic import TemplateView

from articleapp.views import ArticleCreateView, ArticleDetailView, ArticleUpdateView, ArticleDeleteView, ArticleListView

app_name = 'articleapp'

urlpatterns = [
    path('list/', ArticleListView.as_view(), name='list'),

    path('create/', ArticleCreateView.as_view(), name='create'),
    path('detail/<int:pk>',
         ArticleDetailView.as_view(), name='detail'),
    path('update/<int:pk>',
         ArticleUpdateView.as_view(), name='update'),
    path('delete/<int:pk>',
         ArticleDeleteView.as_view(), name='delete'),
]
テンプレートにもリストが入っていますhtmlも作ります.上のアドレスの引用符を参照すると、次のコードを参照する必要があります.したがって、html、css部分をlistページにコピーして挿入します.以下に示します.
{% extends 'base.html' %}
{% load static %}

{% block content %}

<style>
    .container div {
  width: 250px;
  background-color: antiquewhite;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 1rem;
}

.container img {
    width: 100%;
    border-radius: 1rem;
}

</style>
{% if article_list %}
<div class="container">
    {% for article in article_list %}
    <a href="{% url 'articleapp:detail' pk=article.pk%}">
        {% include 'snippets/card.html' with article=article%}
    </a>
    {% endfor %}
  </div>
  <script src="{% static 'js/magicgrid.js' %}"></script>
{% else %}
<div style="text-align: center;">
    <h1>No Articles YET!</h1>
</div>
{% endif%}

{% include 'snippets/pagination.html' with page_obj=page_obj %}
  
  <div style="text-align: center;">
      <a href="{% url 'articleapp:create' %}" class="btn btn-dark rounded-pill col-3 mt-3 mb-3">
          Create Article
      </a>
  </div>
また、jsファイルは下図のようにstaticで単独で作成・管理されています.

次に、ダウンジャケットコードを参照して、長いjsコードをコピーして貼り付け、下部に2つのセルの上のjs写真のコードをコピーします.そしてリストhtmlのscriptラベルにはjsファイルのsrcが含まれています.以下に示します.
<script src="{% static 'js/magicgrid.js' %}"></script>
そして運行すると?下図のようにレイアウトカードがいいです.

Articスパンの実装


まず、モデルは次のとおりです.pyを記入します.
from django.db import models
from django.contrib.auth.models import User

# Create your models here.


class Article(models.Model):
    wrtier = models.ForeignKey(
        User, on_delete=models.SET_NULL, related_name='article', null=True)
    title = models.CharField(max_length=200, null=True)
    image = models.ImageField(upload_to='article/', null=False)
    content = models.TextField(null=True)

    create_at = models.DateField(auto_now_add=True, null=True)
forms.pyファイルも以下のように作成されます.
from django.forms import ModelForm

from articleapp.models import Article


class ArticleCreationForm(ModelForm):
    class Meta:
        model = Article
        fields = ['title', 'image', 'content']
コマンドを実行します.
python manage.py makemigrations
python manage.py migrate
観点もあります.pyでcreateviewとdetailviewを作成します.次のようにします.これはこれまでに創造された論理と同じである.
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from django.http import HttpResponseForbidden
from django.urls import reverse, reverse_lazy
from django.views.generic import CreateView, DetailView, UpdateView, DeleteView, ListView
from django.views.generic.edit import FormMixin
from commentapp.forms import CommentCreationForm
from articleapp.forms import ArticleCreationForm
from articleapp.models import Article

# Create your views here.


@method_decorator(login_required, 'get')
@method_decorator(login_required, 'post')
class ArticleCreateView(CreateView):
    model = Article
    form_class = ArticleCreationForm
    template_name = 'articleapp/create.html'

    def form_valid(self, form):
        temp_article = form.save(commit=False)
        temp_article.user = self.request.user
        temp_article.save()
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('articleapp:detail', kwargs={'pk': self.object.pk})


class ArticleDetailView(DetailView, FormMixin):
    model = Article
    form_class = CommentCreationForm
    context_object_name = 'target_article'
    template_name = 'articleapp/detail.html'
そしてcreatehtmlと詳細.htmlを生成します.これまでと同じように、コードは省略されています.
まだ頭がある.htmlに文章リンクへのタグを表示し、下部の文章を作成するボタンを追加します.実行するとボタンもよく、ボタンをクリックすると文章を書くリンクによく移動できます.

では、updateページも同様に作成されます.表示:updateviewをpyに追加しurlsを使用します.pyの作成後
class ArticleUpdateView(UpdateView):
    model = Article
    context_object_name = 'target_article'
    form_class = ArticleCreationForm
    template_name = 'articleapp/update.html'

    def get_success_url(self):
        return reverse('articleapp:detail', kwargs={'pk': self.object.pk})
投稿にupdateボタンを追加します.次の2枚の写真のようによく動いているのが見えます

同様にdeleteページも作成されます.表示:deleteviewをpyに追加しurlsを使用します.pyを作成し、投稿にdeleteボタンを追加します.
class ArticleDeleteView(DeleteView):
    model = Article
    context_object_name = 'target_article'
    success_url = reverse_lazy('articleapp:list')
    template_name = 'articleapp/delete.html'
では、下の2枚の写真のようにうまく動いています.

ListView、Paginationの概要と応用


これまでaccountアプリケーションとprofileアプリケーションは、ログインしたユーザーのみに記入させるために1 dv 1の関係でviewを作成していましたが、投稿は掲示板形式で作成され、前に作成したものとは異なります.そのため、倉庫が提供するListViewを使用しています.
表示:pyでlistviewを作成します.
class ArticleListView(ListView):
    model = Article
    context_object_name = 'article_list'
    template_name = 'articleapp/list.html'
    paginate_by = 25
もし招待状がないならばまだ招待状がないことを说明して、もし招待状があるならばずっとみんなに招待状を见せます.次に、下図に示すようにtemplatesのsnippetsというディレクトリにcardを配置します.htmlを作成してカードレイアウトの設計を管理します.
<div>
    <img src="{{ article.image.url }} " alt="">
</div>
次に、フラグメントをページングしてページングを実現します.htmlを作成し、次の画像に従って作成します.
<div style="text-align: center; margin: 1rem 0;">
    {% if page_obj.has_previous %}
    <a href="?page={{ page_obj.previous_page_number }} " class="btn btn-secondary rounded-pill">
        {{ page_obj.previous_page_number }}
    </a>
    {% endif %}
    <a href="?page={{ page_obj.number }}" class="btn btn-secondary rounded-pill activate">
        {{ page_obj.number}}
    </a>
    {% if page_obj.has_next %}
    <a href="?page={{ page_obj.next_page_number }}" class="btn btn-secondary rounded-pill">
        {{ page_obj.next_page_number }}
    </a>
    {% endif %}
</div>