[Django] 나만의 사이트 만들기 - 글쓰기
- 공유 링크 만들기
- X
- 이메일
- 기타 앱
[Django] 나만의 사이트 만들기 - 글쓰기
# myApp/views.py from django.shortcuts import render, redirect, get_object_or_404, reverse from django.contrib.auth.models import User from django.utils import timezone from .models import Post def index(request): posts = Post.objects.order_by('-id') return render(request, 'index.html', {'posts':posts}) def post(request): if request.method == 'POST': post = Post() post.main_text = request.POST['main_text'] post.create_user = User.objects.get(username = request.user.get_username()) post.create_date = timezone.datetime.now() post.save() return redirect(reverse('index')) return render(request, 'post.html')
# myApp/urls.py from django.urls import path from . import views urlpatterns = [ path('index/', views.index, name="index"), path('post/', views.post, name="post"), ]
# myApp/models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): main_text = models.CharField(max_length=200) create_date = models.DateTimeField('date published') create_user = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.main_text
# myApp/admin.py from django.contrib import admin from .models import Post # Register your models here. admin.site.register(Post)
{% extends 'base.html' %} {% block content %} {%csrf_token%} {% endblock %}
Integer World Search {% if user.is_authenticated %} {{ user.username }} My Profile New Post Sign Out {% else %} Sign In {% endif %} {% block content %} {% endblock %}
{% extends 'base.html' %} {% load humanize %} {% block content %} {% for post in posts.all %} {{ post.create_user }} {{ post.main_text }} {{ post.create_date | naturaltime }} 댓글 (미구현) {% endfor %} {% endblock %}
myProject/settings.py # 33 ~ 43 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', # 시간 추가 'myApp.apps.MyappConfig', 'myMember.apps.MymemberConfig', ] # 57 ~ 71 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['myProject/templates'], # base.html 경로 설정 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
from http://integer-ji.tistory.com/125 by ccl(A) rewrite - 2020-03-23 23:20:16
- 공유 링크 만들기
- X
- 이메일
- 기타 앱
댓글
댓글 쓰기