Hướng dẫn Django - Python - Day 7: Django Form
Hướng dẫn Django - Python - Day 7: Django Form
Ưu điểm của Django Form:
1. Dễ dàng tạo HTML Form Widget
2. Xác nhận và xử lý dữ liệu theo cấu trúc của Python
3. Tạo form từ models giúp dễ dàng update models từ form.
Các bước thực hiện:
- Trong folder template tạo file: form.html
- Trong first_app tạo file form.py
- Thiết lập form.py như sau:
- Chỉnh sửa file views.py như sau:
- Vào file first_project thêm dòng sau trong urlpattern:
- Chỉnh sửa file form_page.html trong template:
- Để nhập dữ liệu vào database và xóa những gì đã nhập trong form cho lần nhập mới, ta thay đổi hàm form_name_view trong file views như sau:
- Sau khi bạn nhập form, dữ liệu sẽ hiển thị như sau:
Ưu điểm của Django Form:
1. Dễ dàng tạo HTML Form Widget
2. Xác nhận và xử lý dữ liệu theo cấu trúc của Python
3. Tạo form từ models giúp dễ dàng update models từ form.
Các bước thực hiện:
- Trong folder template tạo file: form.html
- Trong first_app tạo file form.py
- Thiết lập form.py như sau:
from django import forms
class FormName(forms.Form):
name = form.CharField()
email = form.EmailField()
text = form.CharField(widget = forms.Textarea)
from django.shortcuts import render
#từ gói http của django lấy ra phương thức HttpResponse-
phương thức gửi về dữ liệu
from django.http import HttpResponse
from . import forms
# Create your views here.
def index(request): #tạo hàm lấy ra dữ liệu từ yêu cầu
my_dict = {'insert_me': "Hello, I am from views.py"}
return render(request, 'first_app/index.html',
context = my_dict)
def form_name_view(request):
form = forms.FormName()
return render(request, 'first_app/form_page.html',
{'form': form})
- Vào file first_project thêm dòng sau trong urlpattern:
url(r'^forms/',views.form_name_view, name="form_name")
- Chỉnh sửa file form_page.html trong template:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Forms</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>
<body>
<h1>Fill in the form</h1>
<div class="container">
<form method="POST">
<!--as_P để mỗi xuống dòng các trường của form-->
{{form.as_p}}
<!--csrf_token để tạo token submit form-->
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="Submit">
</form>
</div>
</body>
</html>
- Để nhập dữ liệu vào database và xóa những gì đã nhập trong form cho lần nhập mới, ta thay đổi hàm form_name_view trong file views như sau:
def form_name_view(request):
form = forms.FormName()
#Đặt điều kiện lấy dữ liệu
if request.method == "POST":
form = forms.FormName(request.POST)
#Kiểm tra nếu dữ liệu nhập vào form hợp lệ
if form.is_valid():
print(" VALIADATION SUCCESS")
#nếu dữ liệu nhập đúng thì quay về
# trống để nhập tiếp lần sau
print("NAME:" + form.cleaned_data['name'])
print("EMAIL:" + form.cleaned_data['email'])
print("TEXT:" + form.cleaned_data['text'])
return render(request, 'first_app/form_page.html',
{'form': form})
Nhận xét
Đăng nhận xét