gpt4 book ai didi

python - 显示 Django 表单结果

转载 作者:行者123 更新时间:2023-12-05 05:18:34 25 4
gpt4 key购买 nike

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

模型.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)

表格.py

from django import forms
from contracts.models import Contract

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

View .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})

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

最佳答案

验证后,表单数据在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})

关于python - 显示 Django 表单结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47601064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com