【问题标题】:Django URL Routing misbehaving, routing to an unanticipated pathDjango URL Routing 行为不端,路由到意外路径
【发布时间】:2014-05-18 23:08:57
【问题描述】:

我对model.py做了一些改动,foreignKey调整。 (我意识到我把它们放在了错误的班级)。删除数据库并从头开始创建一个新数据库,因为我已经很远了。当我觉得我纠正了数据库中的所有内容以运行并再次运行 runserver 时,我收到一个 KeyError 错误,它不应该被定向到.

当我输入 url 127.0.0.1:8000/add_tech/ 或 add_exp/ 时,它会加载正确的表单,当我提交时,它会显示函数收到了术语 techexp 通过 urls.py 中的正则表达式,但令人失望的是堆栈跟踪输出显示不同。

views.py 似乎没有正确路由。我应该遵循哪些步骤来帮助逐步完成和调试?

urls.py 有以下内容

from django.conf.urls import patterns, include, url
from resume.views import add_entry, remove_entry

urlpatterns = patterns('',
    url(r'^add_(\w+)/$',add_entry),
    url(r'^remove_(\w+)/$',remove_entry),
)

它被路由到 resume/ 中的 views.py:(如所见)

def add_entry(request, option):
print "Print Option in Url is:"+option #<----- see console out below.
options={
    'job':add_job(request),
    'exp':add_exp(request),
    'tech':add_tech(request),
    'course':add_course(request),
    'project':add_project(request)
    }
form_html = options[option]    
return form_html

这是打印在控制台中显示的内容,它应该被路由到 add_exp,不确定它是如何被路由到 add_tech,正如你在引发错误时看到的那样。:

[18/May/2014 17:01:21] "GET /add_exp/ HTTP/1.1" 200 1446

Print Option in Url is:**exp**

Internal Server Error: **/add_exp/**
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, \*\*callback_kwargs)

File "/home/asilvajr/Repository/mysite/resume/views.py", line 120, in **add_entry**
    'tech':add_tech(request),

File "/home/asilvajr/Repository/mysite/resume/views.py", line 19, in **add_tech**
    return submit_tech(request)

File "/home/asilvajr/Repository/mysite/resume/views.py", line 76, in **submit_tech**
    if vals['tech_name']:

KeyError: 'tech_name'

---- End Console Output -----

只是表单,在 tech_form 中(应该在提交之前和之后加载):

<form action="/add_tech/" method="POST">
<label for="Tech">Technolgy Used:</label>
    <input type="text" name="tech_name"><br/>
    <label for="Type">Type:</label>
<select name="tech_type">
    <option name="L">Language</option>
    <option name="Fr">Framework</option>
    <option name="T">Tools</option>
    <option name="K">Kits</option>
    <option name="E">Extensions</option>
</select><br/>
<input type="submit" name="submit"><br/>
</form>

只是表单,在exp_form中(应该在提交前后加载):

<form action="/add_exp/" method="POST">
<label for="Event">Event:</label>
    <input type="text" name="event"><br/>
    <label for="Description">Description:</label>
<textarea type="textarea" name="exp_descript"></textarea><br/>
<label for="Technology">Technology Used:</label>
{% for tech in techs %}
<input type="checkbox" class="tech_{{ tech.tech_type }}" name="technologies" value="{{ tech.id }}">{{ tech.name }} :: {{ tech.tech_type }}<br/>
{% endfor %}
<input type="submit" name="submit"><br/>
</form>

add_tech 和 add_exp 都是这样设计的:

def add_tech(request):
    if 'submit' in request.POST:
        return submit_tech(request)
    techs = Technologies.objects.all()
    return render(request, 'tech_form.html',{'techs':techs})

按要求提交技术:

def submit_tech(request):
    vals = request.POST.dict()
    vals['errors']=[]
    if vals['tech_name']:
        try:
            exists=Technologies.objects.get(name=vals['tech_name'])
        except Technologies.DoesNotExist:
            exists=None
        if not exists:
            tech = Technologies(name=vals['tech_name'],tech_type=vals['tech_type'])
            tech.save()
        else:
            vals['errors'].append(exists.name + "already exists as a " + exists.tech_type)
    else:
        vals['errors'].append("Added Nothing, Text Feild was empty")
    vals['techs'] = Technologies.objects.all()
    return render(request, 'tech_form.html', vals)

【问题讨论】:

  • 错误似乎发生在submit_tech 函数内部。你能把那个函数也贴在这里吗?
  • 按要求添加了 Submit_tech @ZZY,我正在查看它,但看起来不错。只是不确定我是否理解为什么当页面应该关注 (anything)_exp 时它被路由到 (anything)_tech,反之亦然。模板与视图不匹配。

标签: python django post http-post


【解决方案1】:

我创建了一个测试项目并复制粘贴您的代码。在这里工作正常,我可以成功 POST 到/add_tech/,并在 DB 中创建了一个新的Technologies

我建议你检查add_exp函数中的render()语句,模板名称是否正确?

另外,还有两个建议: 1)。在add_entry功能中,添加对无效条目名称的处理; 2)。在submit_tech函数的第3行,使用if vals.get('tech_name', None):,否则当有人提交无效表单时代码会引发500错误

【讨论】:

  • 这是一个奇怪的行为,很高兴听到你能够通过@ZZY 让它工作。我可以在上面显示的选项字典中注释一行,然后 add_entry 函数将直接指向 add_tech(),因为它应该。更改键或移动 'exp':add_exp() 在字典中的位置,仍然使其重定向到自身。我现在正在通过 urls.py 解决它。感谢您的建议,这实际上解决了另一个我认为是相关问题的问题。我希望在我工作的时候,我会把它洗掉。
猜你喜欢
  • 2012-07-09
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 2021-06-18
  • 2017-11-10
  • 2021-05-26
  • 2020-01-23
相关资源
最近更新 更多