[웹애플리케이션] 2021.08.19

08/19 class commit 1

  1. 긴 제목 작성시 여백
{% extends 'base.html' %}
{% load static %}

{% block content %}

    <style>

        .container {
            padding: 0;
            margin: 0 auto;
        }

        .container div {
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 1rem;
            flex-direction: column;
        }

        .container img {
            width: 7rem;
            height: 7rem;
            object-fit: cover;
            border-radius: 1rem;

        }

    </style>


    <div class="container my-4">

        {% for project in project_list %}

            <div>
                <a href="{% url 'projectapp:detail' pk=project.pk %}">
                    <img src="{{ project.image.url }}"
                         alt="">
                </a>
                <span class="m-2 NNS_B">{{ project.name | truncatechars:10 }}</span>
            </div>

        {% endfor %}

    </div>

    <script src="{% static 'js/magicgrid.js' %}"></script>

   {% include 'snippets/pagination.html' %}

    <div class="text-center my-5">

        <a href="{% url 'projectapp:create' %}"
                class="btn btn-outline-da rk rounded-pill px-5">
            Create Project
        </a>
    </div>


{% endblock %}


08/19 class commit 2

  1. articleapp/models.py
    project 연결
from django.contrib.auth.models import User
from django.db import models

# Create your models here.
from projectapp.models import Project


class Article(models.Model):
    writer = models.ForeignKey(User,
                               on_delete=models.SET_NULL,
                               related_name='article',
                               null=True)
    project = models.ForeignKey(Project,
                                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=True)
    content = models.TextField(null=True)

    created_at = models.DateField(auto_now_add=True, null=True)

migrate 해줌




  1. articleapp/forms.py
    article 작성시 project도 선택할 수 있도록
from django.forms import ModelForm

from articleapp.models import Article


class ArticleCreationForm(ModelForm):
    class Meta:
        model = Article
        fields = ['title', 'image', 'project', 'content']



  1. projectapp/models.py
from django.db import models

# Create your models here.


class Project(models.Model):
    name = models.CharField(max_length=20, null=False)
    description = models.CharField(max_length=200, null=True)
    image = models.ImageField(upload_to='project/', null=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.name}'

migration 할 필요는 없음 model 에 차이는 없으니



08/19 class commit 3

  1. projectapp/templates/projectapp/detail.html
{% extends 'base.html' %}
{% block content %}

    <div class="text-center mv-500 m-auto">
        <div class="m-5">
                <img src="{{ target_project.image.url }}"
                     class="profile_image m-4"
                     alt="profile image">
                <h2 class="NNS_B">
                    {{ target_project.name }}
                </h2>
                <h5>{{ target_project.description }}</h5>

        </div>
    </div>

    <div>
        {% include 'snippets/list_fragment.html' with article_list=object_list %}
    </div>

{% endblock %}



  1. templates/snippets/list_fragment.html

{% load static %}

    <style>

        .container {
            padding: 0;
            margin: 0 auto;
        }

        .container div {
          width: 45%;
            max-width: 200px;
            box-shadow: 0 0 .5rem grey;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 1rem;
            flex-direction: column;
        }

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

    </style>


    <div class="container my-4">

        {% for article in article_list %}

            <div>
                <a href="{% url 'articleapp:detail' pk=article.pk %}">
                    <img src="{{ article.image.url }}"
                         alt="">
                </a>
                <span>{{ article.title }}</span>
            </div>

        {% endfor %}

    </div>

    <script src="{% static 'js/magicgrid.js' %}"></script>

   {% include 'snippets/pagination.html' %}

    <div class="text-center my-5">
        <a href="{% url 'articleapp:create' %}"
            class="btn btn-dark rounded-pill material-icons">
                brush
        </a>
        <a href="{% url 'articleapp:create' %}"
                class="btn btn-outline-dark rounded-pill px-5">
            Create Article
        </a>
    </div>



  1. projectapp/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

# Create your views here.
from django.urls import reverse_lazy, reverse
from django.utils.decorators import method_decorator
from django.views.generic import CreateView, DetailView, ListView
from django.views.generic.list import MultipleObjectMixin

from articleapp.models import Article
from projectapp.forms import ProjectCreationForm
from projectapp.models import Project


@method_decorator(login_required, 'get')
@method_decorator(login_required, 'post')
class ProjectCreateView(CreateView):
    model = Project
    form_class = ProjectCreationForm
    template_name = 'projectapp/create.html'

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


class ProjectDetailView(DetailView, MultipleObjectMixin):
    model = Project
    context_object_name = 'target_project'
    template_name = 'projectapp/detail.html'
    paginate_by = 20

    def get_context_data(self, **kwargs):
        article_list = Article.objects.filter(project=self.object)
        return super().get_context_data(object_list=article_list, **kwargs)


class ProjectListView(ListView):
    model = Project
    context_object_name = 'project_list'
    template_name = 'projectapp/list.html'
    paginate_by = 20


08/19 class commit 4

mypage 들어갔을 때 작성한 게시글들 뜨도록

  1. accountapp/templates/accountapp/detail.html
{% extends 'base.html' %}
{% block content %}

    <div class="text-center mv-500 m-auto">
        <div class="m-5">
            {% if target_user.profile %}
                <img src="{{ target_user.profile.image.url }}"
                     class="profile_image m-4"
                     alt="profile image">
                <h2 class="NNS_B">
                    {{ target_user.profile.nickname }}
                    {% if target_user == user %}
                    <a href="{% url 'profileapp:update' pk=target_user.profile.pk %}"
                       class="material-icons round_button">
                        edit
                    </a>
                    {% endif %}
                </h2>
                <h5>{{ target_user.profile.message }}</h5>
            {% else %}
            <h2>
                <a href ="{% url 'profileapp:create' %}">
                    Create Profile
                </a>
            </h2>
            {% endif %}
        </div>
        {%  if user == target_user %}
        <div>
            <a href="{% url 'accountapp:update' pk=target_user.pk %}"
               class="material-icons round_button mx-2">
                settings
            </a>

            <a href="{% url 'accountapp:delete' pk=target_user.pk %}"
               class="material-icons round_button mx-2">
                close
            </a>

        </div>

        {% endif %}
    </div>
    <div>
        {% include 'snippets/list_fragment.html' with article_list=object_list %}
    </div>

{% endblock %}



  1. accountapp/views.py
    AccountDetailView 수정
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import render

# Create your views here.
from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic import CreateView, DetailView, UpdateView, DeleteView
from django.views.generic.list import MultipleObjectMixin

from accountapp.decorators import account_ownership_required
from accountapp.forms import AccountCreationForm
from accountapp.models import HelloWorld
from articleapp.models import Article


@login_required(login_url=reverse_lazy('accountapp:login'))
def hello_world(request):
    if request.method == "POST":

        temp = request.POST.get('hello_world_input')

        new_hello_world = HelloWorld()
        new_hello_world.text = temp
        new_hello_world.save()

        return HttpResponseRedirect(reverse('accountapp:hello_world'))

    else:
        hello_world_list = HelloWorld.objects.all()
        return render(request, 'accountapp/hello_world.html',
                      context={'hello_world_list': hello_world_list})


class AccountCreateView(CreateView):
    model = User
    form_class = UserCreationForm
    success_url = reverse_lazy('accountapp:hello_world')
    template_name = 'accountapp/create.html'


class AccountDetailView(DetailView, MultipleObjectMixin):
    model = User
    context_object_name = 'target_user'
    template_name = 'accountapp/detail.html'
    paginate_by = 20

    def get_context_data(self, **kwargs):
        article_list = Article.objects.filter(writer=self.object)
        return super().get_context_data(object_list=article_list, **kwargs)


has_ownership =[login_required, account_ownership_required]


@method_decorator(has_ownership, 'get')
@method_decorator(has_ownership, 'post')
class AccountUpdateView(UpdateView):
    model = User
    form_class = AccountCreationForm
    context_object_name = 'target_user'
    template_name = 'accountapp/update.html'

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


@method_decorator(has_ownership, 'get')
@method_decorator(has_ownership, 'post')
class AccountDeleteView(DeleteView):
    model = User
    context_object_name = 'target_user'
    success_url = reverse_lazy('accountapp:hello_world')
    template_name = 'accountapp/delete.html'

08/19 class commit 5
subscibeapp

  1. python manage.py startapp subscribeapp



  1. web0701_/settings.py
    installed_apps 에 subscribeapp 추가
...

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap4',
    'accountapp',
    'profileapp',
    'articleapp',
    'commentapp',
    'projectapp',
    'subscribeapp',
]
...



  1. web0701_/urls.py

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accountapp.urls')),
    path('profiles/', include('profileapp.urls')),
    path('articles/', include('articleapp.urls')),
    path('comments/', include('commentapp.urls')),
    path('projects/', include('projectapp.urls')),
    path('subscibes/', include('subscribeapp.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# 어떤 경로로 요청이 들어왔을 때 / 어디서 파일을 제공해줄건지



  1. subscribeapp/urls.py 생성 후 작성
urlpatterns = [

]

좋은 웹페이지 즐겨찾기