2014-02-12 78 views
0

我是Django的新手,無法弄清楚爲什麼表單不工作。看起來,表單提交後,即使URL被更改爲/82nsj/update它仍然在視圖中的index方法。Django表單提交url無法正常工作

查看

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

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' 
    ) 
) 

我知道這是行不通的,因爲我有breakpoi nts設置在我的index和我的update中,當我按下提交按鈕後,只有index斷點正在到達。

我在做什麼錯誤是阻止update方法運行表單提交?

回答

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第一URL。

要停止此操作,請爲end of expression包含$

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

現在你/business/<token>/update/不會匹配第一個URL,並隨後將匹配business.views.update