2016-05-27 207 views
1

我有一個插入/更新我的數據庫中的名爲BankAccounts表的視圖...基本上如果info_id傳遞到其功能edit/update如果不是,它有默認值它的一個insert操作django網址:可選參數與默認值始終爲無

def bankcreate(requset , info_id = 0): 

    print(' -----> id is ' + str(info_id)) 
    errors = [] 
    default = None 

    if info_id is not None and info_id > 0 : 
     try: 
      default = BankAccounts.objects.get(id=info_id , user_id=requset.user.id) 
     except BankAccounts.DoesNotExist : 
      default = None 


    if requset.POST : 
     VALIDATIONRULES = {} # some rules here 
     data , errors = validation(requset , VALIDATIONRULES) 

     if not errors : 

      if info_id > 0 and default is not None: 
       ba = default 
      else : 
       ba = BankAccounts() 

      ba.bank_accnumber = data['bank_accnumber'] 
      ba.bank_cartnumber = data['bank_cartnumber'] 
      ba.bank_shabanumber = data['bank_shabanumber'] 
      ba.bank_title = data['bank_title'] 
      ba.user_id = requset.user.id 
      ba.save() 

      return redirect('account-bank') 
     else: 
      default = data 

    return render(requset , 'account/bankcreate-form.html' , 
    {'default':default , 'errors':errors}) 

所以你看到CDAN功能應該可以訪問帶有或不帶info_id 這是我rules.py

urlpatterns = [ 
    url(r'^$', views.index , name='account-home'), 
    url(r'^edit$', views.edit , name='account-edit'), 
    url(r'^bankinfo', views.bankinfo , name='account-bank'), 
    url(r'^bankcreate/(?:/(?P<info_id>[1-9]+)/)?', views.bankcreate , name='account-bankcreate'), 

] 

爲你可以看到我試着寫在最後一行

url(r'^bankcreate/(?:/(?P<info_id>[1-9]+)/)?', views.bankcreate , name='account-bankcreate'), 

一個可選的參數,但它不」工作......而在功能我得到info_id爲None不是事件的定義的默認值在控制檯上0 ...我做錯了什麼?

這是我的樣本網址

http://localhost:8000/account/bankcreate/1/ 

我都試過

url(r'^bankcreate/(?:/(?P<info_id>[1-9]+)/)?/$' 

url(r'^bankcreate/(?:/(?P<info_id>[1-9]+)/)?$' 

,但我得到這個錯誤

Page not found (404) 
Request Method:  GET 
Request URL: http://localhost:8000/account/bankcreate/1/ 

Using the URLconf defined in paypal.urls, Django tried these URL patterns, in this order: 

     ^$ 
     ^admin/ 
     ^account/ ^$ [name='account-home'] 
     ^account/ ^edit$ [name='account-edit'] 
     ^account/ ^email [name='account-email'] 
     ^account/ ^bankinfo [name='account-bank'] 
     ^account/ ^bankcreate/(?:/(?P<info_id>[1-9]+)/)?$ [name='account-bankcreate'] 
     ^account/ ^password [name='account-password'] 
     ^gateway/ 
     ^auth/ 

    The current URL, account/bankcreate/1/, didn't match any of these. 
+0

也許在正則表達式的末尾添加一個美元符號解決您的問題,請張貼按預期不工作的樣本URL。 –

+0

@ArmanOrdookhani thanx,我已經更新了我的問題 – max

回答

1

你的正則表達式中有一個額外的斜槓(第二個)。

變化

url(r'^bankcreate/(?:/(?P<info_id>[1-9]+)/)?$' 

url(r'^bankcreate/(?:(?P<info_id>[1-9]+)/)?$' 
+0

thanx,dorost shod ...我仍然沒有通過參數時獲得'None'而不是'0'作爲默認值,但我猜測那是python! – max