首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >需要Django 'local variable‘表单’赋值前引用‘的帮助

需要Django 'local variable‘表单’赋值前引用‘的帮助
EN

Stack Overflow用户
提问于 2010-10-07 20:27:15
回答 2查看 8.6K关注 0票数 0

我在姜戈遇到了问题。我已经在我的应用程序中创建了一个表单,我可以在其中获取客户的详细信息。现在,我想创建一个允许我编辑表单的表单。然而,当我转到/index/edit_client/1时遇到了一些问题,我得到了这个错误。

代码语言:javascript
运行
复制
local variable 'form' referenced before assignment

我不知道我得到这个错误的原因是什么,但从我所看到的情况来看,它没有任何帮助,除非当然有另一种方法来创建编辑窗体来编辑客户窗体。下面是一些可能对您有帮助的输出。

代码语言:javascript
运行
复制
# urls.py
    urlpatterns = patterns('',
    (r'^index/$', login_required(direct_to_template), { 'template': 'index.html' }),
    (r'^index/clients/$', client_info),
    (r'^index/clients_details/(?P<id>\d+)/$', clients_details),
    (r'^index/edit_client/(?P<id>\d+)/$', edit_client),
)

# views.py
@login_required 
def edit_client(request, id=1):
    clients_list = Client.objects.filter(pk=id)  
    if request.method == 'POST':
        form = ClientForm(request.POST or None)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/index/clients/')
        else: form = ClientForm()
    return render_to_response('edit_client.html', {'form': form},  context_instance=RequestContext(request))

#edit_client.html
{% extends "base.html" %}

{% block content %}
<font face="verdana,news gothic,arial,heltevica,serif">
    <h3>Edit Client</h3>
</font>
<form method= "POST" action="">
    <font face="verdana,news gothic,arial,heltevica,serif">
    <div id="form">
        <table>
            {{form.as_table}}
        </table>
        <div align="center" STYLE=" margin-right:190px">
            <input type="submit" value="Submit" STYLE="background-color:#E8E8E8; color:#181818 "/>
        </div>
    </div>
</form>
{% endblock %}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-10-07 20:30:20

这将始终运行:

代码语言:javascript
运行
复制
return render_to_response('edit_client.html', {'form': form}

但如果request.method不是POST,则不会为form分配任何内容。

修复代码:

代码语言:javascript
运行
复制
@login_required 
def edit_client(request, id=1):
    clients_list = Client.objects.filter(pk=id)  
    form = ClientForm()
    if request.method == 'POST':
       form = ClientForm(request.POST or None)
       if form.is_valid():
           form.save()
           return HttpResponseRedirect('/index/clients/')
    return render_to_response('edit_client.html', {'form': form},  context_instance=RequestContext(request))
票数 5
EN

Stack Overflow用户

发布于 2010-10-07 20:30:36

edit_client方法中,您在响应中传递form,但是,如果该方法不是POST,则不会初始化form

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3881601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档