Django:如何在表单提交上传递变量

时间:2015-07-31 00:04:21

标签: python django forms

我有一个django 1.6.11表格(views.py):

def posneg_nlp(request):
sys_project_name = request.GET.get('project', 'graph') # here oll is ok, it can get correct project value
success = False
monitoring_words = ''
pos_features = ''
neg_features = ''
date_saved = datetime(2015, 7, 29)

print('posneg_nlp form')
print("posneg_nlp request.GET.get('sys_project_name', 'graph')", request.GET.get('project', 'graph'))

if request.method == 'POST':
    posnegnlp_form = PosnegnlpForm(request.POST)
    if posnegnlp_form.is_valid():
        print('posneg_nlp form is_valid')
        success = True
        sys_project_name = sys_project_name
        # here it cannot get project value, it replaced with default:
        print("posneg_nlp form is_valid request.GET.get('sys_project_name', 'graph')", request.GET.get('project', 'graph')) 
        print("sys_project_name ", sys_project_name)
        monitoring_words = posnegnlp_form.cleaned_data['monitoring_words']
        pos_features = posnegnlp_form.cleaned_data['pos_features']
        neg_features = posnegnlp_form.cleaned_data['neg_features']
        print('pos_features:', pos_features, 'neg_features:', neg_features)

        posneg_nlp_filter(sys_project_name, pos_features, neg_features, db_collection=Vkwallpost)
        #get_likes_wallposts_by_owner_id(typeobject='post', owner_id=None, item_id=None, filter_posts='likes')


else:
    posnegnlp_form = PosnegnlpForm()
    success = False

ctx = {'posnegnlp_form': posnegnlp_form, 'sys_project_name': sys_project_name, 'monitoring_words': monitoring_words,
       'pos_features': pos_features, 'neg_features': neg_features, 'success': success}
return render_to_response('choose_nlp_filter.html', ctx, context_instance = RequestContext(request))

这是两个中的第二种形式。从第一个表单开始,我通过模板将变量 sys_project_name 传递给此表单:

                                <div class="rowSubmit">
                                <a style="outline: medium none;" hidefocus="true" href="{{ DOMAIN_URL }}/post/choose_nlp_filter/?project={{ sys_project_name }}" class="btn btn-right"><span class="gradient">К шагу 2. Выбор фильтров&nbsp;</span></a>

                            </div>

当我在表单函数 posneg_nlp(请求)上打印 sys_project_name 的当前值时,它显示正确的值 request.GET.get(&#39; project& #39;,&#39; graph&#39;)等于graph2(在表单呈现时发生)。 但之后 if posnegnlp_form.is_valid():后停止查看它并 request.GET.get(&#39; project&#39;,&#39; graph&#39; )显示未找到的值,等于&#34; graph&#34;。

那么,如何传递变量而不允许重写呢?

1 个答案:

答案 0 :(得分:1)

在第一种情况下,视图正在响应http GET请求,因此request.GET包含您的项目参数。提交表单时,现在视图响应了http POST请求,request.POST包含表单数据。在后一种情况下,如果您希望request.GET仍然包含'project'参数,那么您可以通过表单标记中的form action参数传递它:

form action =“/ some / url /?project = {{sys_project_name}}”