728x90
Python Django Form
Model class 와 유사하게 Form class를 정의함
Form 생성 >> 검증 >> cleaned_data
Model class 생성
myapp/models.py
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=20)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def get_absolute_url(self): # redirect 시 활용
return reverse('myapp:post_detail', args=[self.id])
Form class 생성
myapp/forms.py
from django import forms
from .models import Post
# Form ( 일반)
class PostForm(forms.Form):
title = forms.CharField()
content = forms.CharField(widget=forms.Textarea)
# Model Form ( 모델)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content']
View class | method 생성
myapp/views.py
# Method view
from django.shortcuts import render
def button_method(request):
return render(request, 'button.html')
def output_method(request):
import requests
data = requests.get("https://reqres.in/api/users")
print(data.text)
data = data.text
context = {
'data': data,
}
return render(request, 'button.html', context)
# Class Template view
from django.views.generic import TemplateView
class PostView(TemplateView):
template_name = 'post.html'
# Class Form view
from django.views.generic.ecit import FormView
from django.urls import reverse_lazy
from .forms import PostForm
class PostView(FormView):
form_class = PostForm
template_name = 'post.html'
success_url = reverse_lazy( 'success')
URLconf
myapp/urls.py
from django.conf.urls import path
from . import views
urlpatterns = [
path('', views.button_method),
path('output/', views.output_method, name='script')
path('post/', views.PostView.as_view())
]
Template
myapp/templates/button.html
<!DODTYPE html>
<html>
<head>
<title>Python button script </title>
</head>
<body>
<button onclick="location.href='{% url 'script' %}'">Excute Script </button><ht>
{% if data %}
{{ data | safe }}
{% endif %}
</body>
</html>
myapp/templates/post.html
<!DODTYPE html>
<html>
<head>
<title>Python Class view </title>
</head>
<body>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
댓글