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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17754295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:06:03  来源:igfitidea点击:

Can I have a Django form without Model

pythondjangodjango-modelsdjango-formsdjango-views

提问by AdRoiT

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.

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

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 "

流程 --> 表单提交到一个调用视图的 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

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?

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

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

我知道如何用模型做到这一点,但无法弄清楚!

采纳答案by karthikr

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.

是的。这是非常有可能的。您可以阅读Form objects。这将与您对待 a 的方式相同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'

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>