本文介绍了django表单从cookie获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使django表单从Cookie获取值?我保存用户previuos输入到cookies,如果用户再次打开表单我想显示的值。

How to make django forms get value from cookies? I save user previuos input to cookies and if user opens form again I want to show that values.

现在我手动形式如下:

<select name="transmission_type" class="selectpicker">
    <option value="" selected>Select value</option>
    {% for transmission in transmissions %}
    {% if transmission == request.COOKIES.transmission %}
    <option value="{{ transmission.id }}" selected>{{transmission }}</option>
    {% else %}
    <option value="{{ transmission.id }}">{{transmission }}</option>
    {% endif %}
    {% endfor %}
</select>

我如何在django表单中执行此操作?

How I could do this in django forms?

推荐答案

我自己解决了这个问题。您只需要在视图中为您的表单使用django表单初始属性。

I solved this by myself. You just need to use django forms initial attribute for your form in views.

解决方案示例:

if 'something' in request.COOKIES:
    something = request.COOKIES['something']
else:
    something = ''


form = SomethingForm(initial={'something': something })

这篇关于django表单从cookie获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 02:27