gpt4 book ai didi

python - 我可以有一个没有模型的 Django 表单吗

转载 作者:IT老高 更新时间:2023-10-28 21:55:04 25 4
gpt4 key购买 nike

我的模板中可以有一个没有模型支持的表单吗?我不需要存储数据,只需要该数据在 View 中生成我自己的 POST 请求。

模板 - 带有文本字段的表单。查看 - 从表单中获取数据,并生成另一个请求。

Flow --> 表单提交到一个调用 View 的 url"

def form_handle(request):
if request.method=='POST'
form = request.POST

#blah blah encode parameters for a url blah blah
#and make another post request

但这只会将 csrf 标记放入表单变量中。有什么方法可以在我的 form_handle View 中访问模板的那些文本字段?

我知道如何用模型来做,但无法弄清楚!

最佳答案

是的。这是很有可能的。您可以阅读 Form objects .这将与您处理 ModelForm 的方式相同,只是您不受模型约束,并且您必须显式声明所有表单属性。

def form_handle(request):
form = MyForm()
if request.method=='POST':
form = MyForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
#now in the object cd, you have the form as a dictionary.
a = cd.get('a')

#blah blah encode parameters for a url blah blah
#and make another post request
#edit : added ": " after if request.method=='POST'

class MyForm(forms.Form): #Note that it is not inheriting from forms.ModelForm
a = forms.CharField(max_length=20)
#All my attributes here

在模板中:

<form action="{% url form_handle %}" method="POST">{% csrf_token %}
{{form.as_p}}
<button type="submit">Submit</button>
</form>

关于python - 我可以有一个没有模型的 Django 表单吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17754295/

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