显示Django表单结果

时间:2017-12-01 20:31:41

标签: python django

我有一个Django表单(ModelForm),它有很多字段。当用户按下提交时,这些将保存到数据库中。我正在努力解决的问题是,如何在其他HTML页面中输出/呈现这些结果。

Models.py

from django.db import models

# Create your models here.
class Contract(models.Model):
    name = models.CharField(max_length=200)
    doorNo = models.SlugField(max_length=200)
    Address = models.TextField(blank=True)

Forms.py

from django import forms
from contracts.models import Contract

class GenerateContract(forms.ModelForm):
    class Meta():
        model = Contract
        fields = '__all__'

Views.py

from django.shortcuts import render
from contracts.forms import GenerateContract

# Create your views here.
def index(request):
    return render(request, 'contracts/index.html')

def contractview(request):
    form = GenerateContract()
    if request.method == "POST":
        form = GenerateContract(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print('ERROR')
    return render(request,'contracts/contracts.html',{'form':form})

目前,我正在将应用的“索引”主页作为占位符返回。

2 个答案:

答案 0 :(得分:0)

如果要显示包含已保存值的表单,可以使用表单呈现模板并填充实例输入。像这样:

def whereconditions(n):
    s1 = 'df["thecol"] = np.where('
    L = []
    while n > 0:
        s2 = '(df["a"] >= df["a"].shift('+str(n)+')) &'
        L.append(s2)
        n = n -1
    s3 = ",'istrue','isnottrue')"
    r = s1+str([x for x in L]).replace("'","").replace(",","").replace("&]","")+s3
    return str(r.replace("([(","(("))
call = whereconditions(10)
exec(call)

答案 1 :(得分:0)

验证后,表单数据可在form.cleaned_data字典中找到。因此,您可以将其传递回模板并按您认为合适的方式显示。

from django.shortcuts import render
from contracts.forms import GenerateContract

# Create your views here.
def index(request):
    return render(request, 'contracts/index.html')

def contractview(request):
    form = GenerateContract()
    if request.method == "POST":
        form = GenerateContract(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return render(request,'contracts/contracts.html',{'form_data': form.cleaned_data})
        else:
            print('ERROR')
    return render(request,'contracts/contracts.html',{'form':form})