class Article(models.Model):
...
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
$ python manage.py makemigrations
기존에 존재하는 테이블은 데이터가 없는데 NOT_NULL조건인데 DEFAULT 값이라도 줄래? 아니면 직접 모델을 수정 할래?
default 값을 2로 줄게요
참고_요청으로 값을 넘기는 방법 3가지
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')
# exclude에 user 추가해주기
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = '__all__'
exclude = ['created_at', 'updated_at','user']
user_id 마지막에 제대로 6이 들어간 것을 알 수 있다.
6번째 사용자 정보가 일치함을 확인
...
<p>{{ article.user.username }}</p>
...
{% 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>
...
{% if article.user == request.user %}
<form action="{% url 'articles:update' article.pk %}">
<input type="submit" value="수정">
</form>
{% endif %}
...
원하는 상태 코드를 반환할 수도 있다. 사용자의 글이 아닌 경우 막기위해서 구현하므로 403 forbidden이 적당하다.
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 활용하기
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
Comment | User |
---|---|
id | id |
content | username |
created_at | first_name |
updated_at | last_name |
User의 id | 기타 칼럼 생략 |
class Comment(models.Model):
...
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
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)
...
{% 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 %}
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