我是 python 和 django 的新手,在将 html 页面的各个字段存储到数据库中时遇到了困难。例如,我有一个包含 5 个字段和一个提交按钮的 html 页面。在提交表单时,我希望 html 表单中的所有值都应该存储在给定数据库的表中。请帮助我。
问问题
6150 次
2 回答
1
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>
于 2013-01-25T16:48:19.317 回答