如何使用django python从html表单中获取数据 [英] how to get value from html form into database using django python
本文介绍了如何使用django python从html表单中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一个HTML页面,其中包含5个字段和一个提交按钮。在提交表单时,我希望将html表单中的所有值存储在给定数据库的表中。
请帮助我。
解决方案
models.py $ b $来自django.contrib.auth.models的b
从django.db导入模型
class AllocationPlan(models.Model)的用户
:
user = models.ForeignKey (用户)
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
view.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
< form method =post> {%csrf_token%}
{%表单中的字段%}
{{field}}
< input type =submitvalue = 提交/>
{%endfor%}
< / form>
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
<form method="post">{% csrf_token %}
{% for field in form %}
{{field}}
<input type="submit" value="Submit"/>
{% endfor %}
</form>
这篇关于如何使用django python从html表单中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文