본문 바로가기

[djago] 장고 관련 정리-Create, FormView 사용 법 정리

ironwhale 2021. 3. 3.

간단하게 formView를 사용하여 모델에 데이터를 입력하는 패턴관련 정리입니다. 

 

1. 모델 생성

model.py

from django.db import models

# Create your models here.

class TodoList(models.Model):
    contents = models.CharField(max_length=255)
    isDone = models.BooleanField(default=False)

 

 

2. forms.py 작성

from django import forms

class InputForm(forms.Form):
    contents = forms.CharField(max_length=255, label='to Do List!!')

    def clean(self):
        cleaned_data = super().clean()
        self.contents = cleaned_data.get("contents")

        if self.contents :
            print("통과",self.contents)
        else :
            self.add_error('contents',"할일을 입력하세요")

3. View.py 작성

from django.shortcuts import render
from django.views.generic import ListView, FormView
from .models import TodoList
from .forms import InputForm
from django.urls import reverse_lazy
# Create your views here.

class TodoListView(ListView):
    template_name = "todolist.html"
    model = TodoList
    context_object_name = "todolist"

   
class InputDoList(FormView):
    template_name = 'input.html'
    form_class = InputForm
    success_url = reverse_lazy('todolist:todolist_home')

    def form_valid(self, form):
        contents = form.contents
        print(contents)
        toDoList = TodoList(contents=contents)
        toDoList.save()
        return super().form_valid(form)

4. template 작성

<head>
    <title>할일 리스트 입력</title>
</head>
<body>
    <h1>할일 리스트 입력 </h1>
    <div>   
        <form action='./' method="POST">
            {% csrf_token %}
            {% for field in form %}
                <label for ="{{ field.id_for_label}}">{{field.label}}</label>
                <input type="{{ field.field.widget.input_type }}" id="{{ field.id_for_label }}" name="{{field.name}}" >
                {% if field.errors %}
                <span style="color: red">{{field.errors}}</span>
                {% endif %}

            {% endfor %}
            <button type='submit'>입력</button>
        </form>
    </div>

</body>

댓글