반응형
CodingEntrepreneurs Django 강의 정리
form에 입력 받은 데이터를 저장하고 새로운 페이지를 갱신>
forms>
from django import forms
class BlogPostForm(forms.Form):
title = forms.CharField()
slug = forms.SlugField()
content = forms.CharField(widget=forms.Textarea)
create.html>
{% extends "form.html" %}
form.html>
{% extends "base.html" %}
{% block content %}
{% if title %}
<h1>{{ title }}</h1>
{% endif %}
<form method="POST" action="."> {% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
{% endblock %}
views>
from django.http import Http404
from django.shortcuts import render, get_object_or_404
# Create your views here.
from .models import BlogPost
from .forms import BlogPostForm
# CRUD
# GET -> Retrieve / List
# POST -> Create / Update / DELETE
# Create Retrieve Update Delete
def blog_post_list_view(request):
# list out objects
# could be search
qs = BlogPost.objects.all() # queryset -> list of python object
template_name = "blog/list.html"
context = {"object_list": qs}
return render(request, template_name, context)
def blog_post_create_view(request):
# create objects
# ? use a form
form = BlogPostForm(request.POST or None)
if form.is_valid():
obj = BlogPost.objects.create(**form.cleaned_data)
form = BlogPostForm()
template_name = "form.html"
context = {"form": form}
return render(request, template_name, context)
def blog_post_detail_view(request, slug):
# 1 object -> detail view
obj = get_object_or_404(BlogPost, slug=slug)
template_name = "blog/detail.html"
context = {"object": obj}
return render(request, template_name, context)
def blog_post_update_view(request):
obj = get_object_or_404(BlogPost, slug=slug)
template_name = "blog/update.html"
context = {"object": obj, "form": None}
return render(request, template_name, context)
def blog_post_delete_view(request):
obj = get_object_or_404(BlogPost, slug=slug)
template_name = "blog/delete.html"
context = {"object": obj}
return render(request, template_name, context)
반응형
'Python_WEB > Try_Django' 카테고리의 다른 글
[Django]Validate Data on Fields (0) | 2020.06.21 |
---|---|
[Django]Model Form (0) | 2020.06.21 |
[Django]A Django Form (0) | 2020.06.17 |
[Django]Submit Raw HTML Form (0) | 2020.06.17 |
[Django]In App Templates (0) | 2020.06.17 |