You can use django's own rendering template, but it is not as good-looking as the current front-end framework renders, so we use attrs
parameters, the code is as follows:
Contents of this article
Write the form class
First, create a forms.py file in your current app, and enter the following content:
from django import forms
class TaskForm(forms.Form):
task_domain = forms.CharField(label="", widget=forms.TextInput(attrs={
'class':'form-control'}), max_length=50)
Two points:
- No label is required, the label must be controlled to be empty
- Control the input tag class as the css rendered by the front end, which is processed by widget
Final rendering effect
<input type="text" name="task_domain" class="form-control" maxlength="50" required="" id="id_task_domain">
View processing
In the view file view.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import NameForm
def get_name(request):
# 如果form通过POST方法发送数据
if request.method == 'POST':
# 接受request.POST参数构造form类的实例
form = NameForm(request.POST)
# 验证数据是否合法
if form.is_valid():
# 处理form.cleaned_data中的数据
# ...
# 如果是通过GET方法请求数据,返回一个空的表单
else:
form = NameForm()
return render(request, 'form.html', {
'form': form})
Template usage
In Django
the template, we only need to process as follows to get a complete HTML page:
<form action="/" method="post">
{
% csrf_token %}
{
{
form }}
<input type="submit" value="Submit" />
</form>