我可以有一个没有模型的 Django 表单吗 [英] Can I have a Django form without Model

查看:20
本文介绍了我可以有一个没有模型的 Django 表单吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模板中可以有一个没有模型支持的表单吗?我不需要存储数据,只需要这些数据在视图中生成我自己的 POST 请求即可.

Can I have a Form in my template which is not backed by a model. I do not need to store the data just need that data to generate a POST request of my own in the view.

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

Template - The form with text fields. View - get data from form, and generate another request.

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

Flow --> Form submit takes to a url which calls the view "

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 视图中访问模板的那些文本字段吗?

but this puts only the csrf token into the form variable. Is there some way I can access those text fields of the template in my form_handle view?

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

I know how to do it with a model but couldn't figure this out!

推荐答案

是的.这是非常有可能的.您可以阅读表单对象.这将与您对待 ModelForm 的方式相同,只是您不受模型的约束,并且您必须显式声明所有表单属性.

Yes. This is very much possible. You can read up on Form objects. It would be the same way you would treat a ModelForm, except that you are not bound by the model, and you have to explicitly declare all the form attributes.

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>

这篇关于我可以有一个没有模型的 Django 表单吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆