1:N (User - Article/Comment)

Hvvany·2022년 10월 26일
0

django

목록 보기
9/10

Article과 User간 모델 관계 설정

Article 모델에 User모델 참조 외래 키 작성

articles/models.py

class Article(models.Model):
    ...
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

makemigrations/migrate

$ python manage.py makemigrations

기존에 존재하는 테이블은 데이터가 없는데 NOT_NULL조건인데 DEFAULT 값이라도 줄래? 아니면 직접 모델을 수정 할래?

default 값을 2로 줄게요

참고_요청으로 값을 넘기는 방법 3가지

유저를 선택하면 이상! 로그인 사용자가 자동으로 저장되도록

수정 전 선택 가능한 user

articles/views.py

def create(request):
  if request.method == 'POST':
    article_form = ArticleForm(request.POST, request.FILES)
    if article_form.is_valid():
      article = article_form.save(commit=False)
      article.user = request.user
      article.save()
      return redirect('articles:index')

articles/forms.py

# exclude에 user 추가해주기

class ArticleForm(forms.ModelForm):
  class Meta:
    model = Article
    fields = '__all__'
    exclude = ['created_at', 'updated_at','user']

articles_article 테이블

user_id 마지막에 제대로 6이 들어간 것을 알 수 있다.

accounts_user 테이블

6번째 사용자 정보가 일치함을 확인

articles/index.html에 작성자 추가

	...
	<p>{{ article.user.username }}</p>
	...

accounts/detail.html에 사용자가 작성한 모든 글 띄우기

{% extends 'base.html' %}
{% load django_bootstrap5 %}

{% block body %}
<h1>{{ user.username }} 님의 페이지</h1>

<h2>작성한 모든 글</h2>
{% for article in user.article_set.all %}
<a href={% url 'articles:detail' article.pk %}>{{article.title}}</a>
{% endfor %}
{% endblock body %}

순서 메기기, 전체 개수 띄우기

<h2>작성한 모든 글</h2>
<p class='text-muted'>{{ user.article_set.count }}개를 작성하였습니다.</p>
{% for article in user.article_set.all %}
<p>
  {{ forloop.counter }}
  <a href={% url 'articles:detail' article.pk %}>{{article.title}}</a>
</p>

본인이 작성한게 아닌 글 수정 막기

Front_end 단에서 작업

articles/detail.html

	...
  {% if article.user == request.user %}
    <form action="{% url 'articles:update' article.pk %}">
      <input type="submit" value="수정">
    </form>
  {% endif %}
	...

Back_end 단에서 작업

response status codes

원하는 상태 코드를 반환할 수도 있다. 사용자의 글이 아닌 경우 막기위해서 구현하므로 403 forbidden이 적당하다.

articles/views.py_update

def update(request, pk):
  article = Article.objects.get(pk=pk)
  if request.user == article.user:
    if request.method == 'POST':
      ...
  else:
    from django.http import HttpResponseForbidden
    return HttpResponseForbidden()

👉 django HttpResponse subclasses

다른 방법

from django.contrib import messages
...
  else:
    # from django.http import HttpResponseForbidden
    # return HttpResponseForbidden()
    messages.warning(request,'작성자만 수정할 수 있습니다')
    return redirect('articles:detail', article.pk)

django messages 활용하기

👉 Django Messages Framework

articles/detail.html

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}



Comment와 User간 모델 관계 설정

테이블

CommentUser
idid
contentusername
created_atfirst_name
updated_atlast_name
User의 id기타 칼럼 생략

Comment 모델에 User모델 참조 외래 키 작성

articles/models.py

class Comment(models.Model):
    ...
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

makemigrations/migrate

articles/views.py

def comment_create(request, pk):
  article = Article.objects.get(pk=pk)
  comment_form = CommentForm(request.POST)
  if comment_form.is_valid():
    comment = comment_form.save(commit=False)
    comment.article = article
    comment.user = request.user
    comment.save()
  return redirect('articles:detail', article.pk)

articles/detail.html

...
{% for comment in comments %}
    <p>{{ comment.content }} | {{ comment.user.username }}</p>
    {% empty %}
      <p>댓글이 없습니다.</p>
    {%endfor%}
...

댓글에 작성자 이름이 뜨는것을 알 수 있다.

댓글 입력을 로그인 사람만 볼 수 있게

<h2>댓글</h2>
    {% if request.user.is_authenticated %}
    <form action="{% url 'articles:comment_create' article.pk %}" method='POST'>
      {% csrf_token %}
      {% bootstrap_form comment_form layout='inline' %}
      {% bootstrap_button button_type='submit' content='OK' %}
    </form>
	{% endif %}
profile
Just Do It

1개의 댓글

comment-user-thumbnail
2023년 5월 14일

These companies take the stress out of auto shipping by handling all of the logistical details for you. In this blog post, we'll take a closer look at what hassle-free auto car shipping entails and why it may be the best option for you.
https://www.youtube.com/watch?v=MTrl-UO6HJE

답글 달기