Django表单提交URL不起作用

时间:2014-02-12 17:10:07

标签: python django forms

我是Django的新手,无法弄清楚为什么我的表单不起作用。似乎在表单提交后,即使将网址更改为/82nsj/update,它仍然会转到视图中的index方法。

视图

from business.models import Business, Token
from django.shortcuts import render
from business.forms import BusinessForm

def index(request, token):
    try:
        business = Business.objects.get(token__token=token)
    except Token.DoesNotExist:
        business = None
    except Business.DoesNotExist:
        business = None

    form = BusinessForm(instance=business)
    return render(request, 'business/index.html', {'form': form})

def update(request, token):
    try:
        business = Business.objects.get(token__token=token)
    except Token.DoesNotExist:
        business = None
    except Business.DoesNotExist:
        business = None

    form = BusinessForm(request.POST, instance=business)
    if form.is_valid():
        form.save()
        return render(request, 'business/index.html', {'form': form})

网址

url(r'^$', 'business.views.index', name='home'),
url(r'^business/(?P<token>\w+)/', 'business.views.index', name='business'),
url(r'^business/(?P<token>\w+)/update/', 'business.views.update', name='business_update'),

表单

self.helper = FormHelper(self)
self.helper.form_class = 'form-horizontal'
self.helper.form_action = 'update/'
self.helper.form_method = 'post'
self.helper.layout = Layout(
    HTML("<p class='alert-info alert'>Please confirm your business contact information is updated and correct.</p>"),
    Div(
        'my',
                'fields',
        FormActions(
            Submit('save_changes', 'Save changes', css_class="btn-primary"),
        ),
        css_class='row-fluid'
    )
)

我知道这不起作用,因为我在index和我的update设置了断点,在按下提交按钮后,只有index断点到达。< / p>

我做错了什么阻止了update方法在表单提交上运行?

1 个答案:

答案 0 :(得分:2)

这可能是您url(...正则表达式的问题。

Django会转到匹配的第一个网址,如果你有这个

url(r'^business/(?P<token>\w+)/', 'business.views.index', name='business'),
url(r'^business/(?P<token>\w+)/update/', 'business.views.update', name='business_update'),

转到/business/<token>/anything_goes_here将始终转到business.views.index

要停止此操作,请为$添加end of expression

url(r'^business/(?P<token>\w+)/$', 'business.views.index', name='business'),

现在,您的/business/<token>/update/与第一个网址不匹配,然后与business.views.update匹配。