# articles > urls.py
더보기
from django.urls import path
from . import views
app_name = 'articles'
urlpatterns = [
# ''는 메인페이지를 의미한다.
path('', views.index, name='index'),
path('<int:pk>/', views.detail, name='detail'),
path('new/', views.new, name='new'),
path('create/',views.create, name='create'),
path('<int:pk>/delete', views.delete, name='delete'),
path('<int:pk>/edit', views.edit, name='edit'),
]
# articles > views.py
더보기
from django.shortcuts import render, redirect
from .models import Article
def index(request):
articles = Article.objects.all()
context = {
'articles' : articles,
}
return render(request, 'articles/index.html', context)
def detail(request, pk):
article = Article.objects.get(pk=pk)
context = {
'article': article,
}
return render(request, 'articles/detail.html', context)
def new(request):
return render(request, 'articles/new.html')
def create(request):
# print(request.GET) # <QueryDict: {'title': ['제목'], 'content': ['내용']}>
title = request.POST.get('title')
content = request.POST.get('content')
article = Article()
article.title = title
article.content = content
article.save()
# return redirect('주소','argument나 변수들','')
return redirect('articles:detail', article.pk)
# 여기서 pk는 variable routing 변수이다
def delete(request, pk):
# 조회를 먼저
# 몇번 글 삭제할거야?
article = Article.objects.get(pk=pk)
article.delete()
return redirect('articles:index')
# render는 페이지 주기
# redirect는 되돌리기
def edit(request, pk):
article = Article.objects.get(pk=pk)
context = {
'article': article,
}
return render(request, 'articles/edit.html', context)
# articles > templates > articles > edit.html
더보기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Edit</h1>
<form action="{% url "articles:update" article.pk %}" method="POST">
{% csrf_token %}
<input type="text" name="title" value="{{ article.title }}">
<textarea name="content">{{ article.content }}</textarea>
<input type="submit">
</form>
</body>
</html>
'WEB > Django prac' 카테고리의 다른 글
[Django prac][Form] 1. Form Class (0) | 2024.03.28 |
---|---|
[Django prac][ORM with View] CRUD 구현 14_Update (0) | 2024.03.28 |
[Django prac][ORM with View] CRUD 구현 12_ Delete (0) | 2024.03.28 |
[Django prac][ORM with View] CRUD 구현 11_ Delete (0) | 2024.03.28 |
[Django prac][ORM with View] CRUD 구현 10 (0) | 2024.03.28 |