【问题标题】:Can I have a Django form without Model我可以有一个没有模型的 Django 表单吗
【发布时间】:2013-07-19 05:21:52
【问题描述】:

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

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

Flow --> 表单提交到一个调用视图的 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 视图中访问模板的那些文本字段?

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

【问题讨论】:

    标签: python django django-models django-forms django-views


    【解决方案1】:

    是的。这是很有可能的。你可以阅读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>
    

    【讨论】:

    • 可以在没有model 的情况下在admin 中访问view 吗?
    猜你喜欢
    • 2022-01-04
    • 2017-04-22
    • 2018-05-27
    • 2014-04-19
    • 2023-03-15
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    相关资源
    最近更新 更多