如何使用django python从html表单获取值到数据库

时间:2013-01-25 12:39:01

标签: python django

我是python和django的新手,我很难将html页面的各个字段存储到数据库中。 例如,我有一个html页面,其中包含5个字段和一个提交按钮。在提交表单时,我希望html表单中的所有值都应该存储在给定数据库的表中。 请帮助我。

2 个答案:

答案 0 :(得分:1)

您应该从模型的角度来处理这个问题,模型将模型的属性映射到数据库字段,并且可以方便地用于创建表单。这称为Object-Relational Mapping

首先在app的文件夹中创建(或修改)models.py,然后在那里声明模型(基本上是你想要存储的字段)。如上所述,请参阅Django的creating formsmodel-form mapping教程。

答案 1 :(得分:0)

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>