(프로젝트 명은 myproject, 앱 명은 blog 사용하겠습니다!)
가상환경 생성 및 켜기
python -m venv <가상환경_이름>
source <가상환경_이름>/Scripts/activate
장고 설치 및 프로젝트 / 앱 설정
pip install django
django-admin startproject myproject
cd <프로젝트명>
python manage.py startapp blog
settings.py
에 앱 등록INSTALLED_APPS = [
'blog',
]
static / media 관련 설정
#settings.py
import os
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'blog', 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
#settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
#myproject/urls.py
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
templates 관련 설정
blog/templates/blog
폴더 생성
settings.py
에 templates 경로 설정
TEMPLATES = [
'DIRS': [
os.path.join(BASE_DIR, 'myproject', 'templates')
]
]
데이터베이스 초기화
python manage.py migrate
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date = models.DateTimeField(auto_now_add=True)
python manage.py makemigrations
python manage.py migrate
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
pass
templates/blog/home.html
<a href="{% url 'new' %}">새 글 작성하기 HTML form</a>
templates/blog/new.html
<form action="{% url 'create' %}" method="POST">
{% csrf_token %}
<label for="title">제목</label>
<input type="text" name="title">
<label for="content">본문</label>
<textarea name="content" id="" cols="30" rows="10"></textarea>
<input type="submit" value="제출">
</form>
views.py
from .models import Post
from django.utils import timezone
def new(request):
return render(request, 'blog/new.html')
def create(request):
if request.method == 'POST':
post = Post()
post.title = request.POST['title']
post.content = request.POST['content']
post.date = timezone.now()
post.save()
return redirect('home')
urls.py
from . import views
urlpatterns = [
path('new/', views.new, name='new'),
path('create/', views.create, name='create'),
]
templates/blog/home.html
<a href="{% url 'form' %}">새 글 작성하기 django form</a>
forms.py
생성하기from django import forms
class PostForm(forms.Form):
title = forms.CharField()
content = forms.CharField(widget = forms.TextArea)
views.py
from .forms import PostForm
def form(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = Post()
post.title = form.cleaned_data['title']
post.content = form.cleaned_data['content']
post.save()
return redirect('home')
else:
form = PostForm()
return render(request, 'blog/form_create.html', {'form': form})
form.html
<form action="" method="POST">
{% csrf_token %}
<table>
{{form.as_table}}
</table>
<input type="submit" value="제출">
</form>
templates/blog/home.html
<a href="{% url 'modelForm' %}">새 글 작성하기 django model form</a>
urls.py
urlpatterns = [
path('modelForm', views.modelForm, name='modelForm')
]
forms.py
생성하기from django import forms
from .models import Post
class PostModelForm(forms.ModelForm):
class Meta:
model = Post
#fields = '__all__'
fields = [title, content]
views.py
from .forms import PostModelForm
def modelForm(request):
if request.method == 'POST':
form = PostModelForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = PostModelForm()
return render(request, 'blog/form.html', {'form': form}
detail page를 가져오는 부분
urls.py
from . import views
urlpatterns = [
path('detail/<int:post_id>', views.detail, name='detail'),
]
views.py
from django.shortcuts import get_object_or_404
from .models import Post
def detail(request, post_id):
post = get_object_or_404(Post, pk=post_id)
return render(request, 'detail.html', {'post': post}
detail.html
<div>{{post.id}}</div>
<div>{{post.title}}</div>
<div>{{post.content}}</div>
추가 예정
추가 예정