How to pass variables with spaces through URL in :Django

风流意气都作罢 提交于 2019-12-21 12:03:03

问题


I am having trouble in passing variables with spaces in them through the urls. Now Suppose I have an object

class Kiosks(models.Model):
    name = models.CharField(max_length = 200, unique = True)
    owner = models.ForeignKey(User)

Now the "name" entered for kiosk is say "Akash Deshpande" and saved. Now while redirecting to a new page in the views, i am using the "kiosk name " i.e.

 messages.success(request,"Kiosk edited successfully") 
 return HttpResponseRedirect('/kiosks/'+kiosk.name+'/')

The view which caters to this url is as follows:

def dashboard(request, kiosk_name):
    kiosk =Kiosks.objects.get(name__iexact = kiosk_name)
    deal_form = DealsForm(kiosk=kiosk)
    code_form = CodeForm()
    unverified_transactions = get_unverified_transactions(kiosk)
    return render(request,'kiosks/dashboard.html',{'kiosk':kiosk, 
                                                   'deal_form' : deal_form,
                                                   'code_form' : code_form,
                                                   'unverified_transactions' : unverified_transactions})

The main urls.py simply directs everything with "kiosks" to bellow urls kiosks urls.py

urlpatterns = patterns('kiosks.views',url(r'^(\w+)/$', 'dashboard'),)

Now instead of going to this page it is giving an error "Page not found". How do i pass variables which have space in them ? Is the question clear? Any help will be highly appreciated.


回答1:


Allow spaces in your regex.

urlpatterns = patterns('kiosks.views', url(r'^([\w ]+)/$', 'dashboard'),)

And for the love of Pete, use reverse(). It will help you catch silly mistakes like this.




回答2:


yup .. allow spaces in your regex .. something like this works for me ..

url(r'^find-interiordesigners/state-(?P<state>.+?)/$',DesignersByCategoryCityState.as_view(),name='findInterior-state'),


来源:https://stackoverflow.com/questions/8238268/how-to-pass-variables-with-spaces-through-url-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!