Djangoで作成、Read
CRUD with views
READ
app_name = 'articles'
urlpatterns = [
path('', views.index, name='index'),
]
def index(request):
# 전체 게시글 조회(오름차순)
# articles = Article.objects.all()
# 전체 게시글 조회(내림차순 1, python으로 조작)
# articles = Article.objects.all()[::-1]
# 전체 게시글 조회(내림차순 2, DB가 조작)
articles = Article.objects.order_by('-pk')
# 조회해서 할당한 쿼리셋 데이터를 context로 넘김
context = {
'articles': articles,
}
return render(request, 'articles/index.html', context)
{% block content %}
<h1>Articles</h1>
<a href="{% url 'articles:new' %}">NEW</a>
<hr>
{% for article in articles %}
<p>글 번호: {{ article.pk }}</p>
<p>글 제목: {{ article.title }}</p>
<p>글 내용: {{ article.content }}</p>
<a href="{% url 'articles:detail' article.pk %}">DETAIL</a>
<hr>
{% endfor %}
{% endblock content %}
python manage.py runserver
CREATE
app_name = 'articles'
urlpatterns = [
path('', views.index, name='index'),
path('new/', views.new, name='new'),
path('create/', views.create, name='create'),
]
def new(request):
return render(request, 'articles/new.html')
def create(request):
title = request.POST.get('title')
content = request.POST.get('content')
# 1
# article = Article()
# article.title = title
# article.content = content
# article.save()
# 2
article = Article(title=title, content=content)
article.save()
# 3
# Article.objects.create(title=title, content=content)
# return redirect('/articles/')
return redirect('articles:detail', article.pk)
#new.html
{% extends 'base.html' %}
{% block content %}
<h1>NEW</h1>
<hr>
<form action="{% url 'articles:create' %}" method="POST">
{% csrf_token %}
<label for="title">Title: </label>
<input type="text" id="title" name="title"><br>
<label for="content">Content: </label>
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit">
</form>
{% endblock content %}
#create.html
{% extends 'base.html' %}
{% block content %}
<h1>성공적으로 글이 작성되었습니다.</h1>
{% endblock content %}
Reference
この問題について(Djangoで作成、Read), 我々は、より多くの情報をここで見つけました https://velog.io/@holawan/Django에서-CreateRead-해보기テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol