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

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

问题描述

我可以在我的模板中找到没有模型支持的表单。我不需要存储数据,只需要这些数据就可以在视图中生成我自己的POST请求。



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



流程 - >表单提交到一个调用视图的URL

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

#blab blah编码一个url blah的参数blah
#和另一个发布请求

但这只会将csrf标记放入表单变量
有一些方法可以在form_handle视图中访问模板的文本字段吗?



我知道如何用模型来做,但是无法理解这一点!

解决方案

是的,这是您可以阅读表单对象。除了你不受模型约束,你将会像 ModelForm 一样,你必须明确地声明所有的e形式属性。

  def form_handle(request):
form = MyForm()
if request.method ==' POST'
form = MyForm(request.POST)
如果form.is_valid():
cd = form.cleaned_data
#now在对象cd中,您的表单为一本字典。
a = cd.get('a')

#blah blah编码一个url的参数blah blah
#和另一个发布请求

  class MyForm表单):#注意它不是从forms继承.ModelForm 
a = forms.CharField(max_length = 20)
#所有我的属性在这里

在模板中:

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


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 --> 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

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!

解决方案

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

and

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

In the template:

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

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

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