max max - 6 months ago 14
Python Question

django urls : optional argument with default value is always None

i have a view for insert / update a table called

BankAccounts
in my database ... basically if
info_id
is passed to function its a
edit/update
if not and it has default value its a
insert
operation

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


so as you cdan see the function should be accessible with or without the info_id
this is my 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'),

]


as you can see i'm trying to write a optional argument on the last line

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


but it doesnt' work ... and on the console in the function i get info_id as
None
not event the defined default value of 0 ... what am i doing wrong ?

this is my sample url

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


i've tried both

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


and

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


but i got this error

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.

Answer

You have an extra slash in your regexp (second one).

Change

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

to

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