python接收html表单_如何使用django python从html表单中获取数据

I am newbie in python and django and I am facing difficulty in storing various fields of html page into database.

E.g, I have a html page which contains 5 fields and one submit button . On submitting the form, I want all values from html form should be stored in table of the given database.

Please help me in this.

解决方案models.py

from django.contrib.auth.models import User

from django.db import models

class AllocationPlan(models.Model):

user = models.ForeignKey(User)

name = models.CharField(max_length=50)

data = models.CharField(max_length=4096)

total = models.DecimalField(max_digits=10, decimal_places=2)

forms.py

from django import forms

from django.forms import ModelForm

from app_name.models import AllocationPlan

class AllocationPlanForm(ModelForm):

class Meta:

model = AllocationPlan

views.py

from django.shortcuts import render

from app_name.forms import AllocationPlanForm

def add(request):

if request.method == 'POST':

form = AllocatinPlanForm(request.POST)

if form.is_valid():

form.save()

return render(request, 'page.html', {

'form': AllocationPlanForm()

})

page.html

{% csrf_token %}

{% for field in form %}

{{field}}

{% endfor %}

下面是一个简单的Django表单处理示例: 1. 定义表单类 ```python from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea) ``` 2. 创建表单视图函数 ```python from django.shortcuts import render from .forms import ContactForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] # 处理表单数据 else: form = ContactForm() return render(request, 'contact.html', {'form': form}) ``` 3. 创建表单模板 ```html {% extends 'base.html' %} {% block content %} <h1>Contact Us</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form> {% endblock %} ``` 在表单视图函数,我们首先检查请求的方法是否为POST。如果是,则创建一个表单对象,并使用表单数据验证其有效性。如果表单数据有效,则从表单对象提取数据并处理它们。否则,我们将使用无效表单对象呈现表单模板。 在表单模板,我们使用Django的模板标记和过滤器来呈现表单。我们使用`form.as_p`过滤器将表单渲染为HTML段落。我们还使用`{% csrf_token %}`标记为表单添加CSRF令牌,以确保表单在提交时不受到跨站点请求伪造攻击的影响。最后,我们在表单上添加一个提交按钮。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值