Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define url which accept everykind of strings in django

In django, I defined url like that

(r'^checkstring/(?P<string>\w+)/$',views.check_str,name='check str')

But, When i enter string inputs like ibrahim.yilmaz, ibrahi!m or [email protected], it returns http 404. So how can i write the url which accept everykind of string?

any help will be appreciated.

İbrahim

like image 212
ibrahimyilmaz Avatar asked Sep 23 '11 20:09

ibrahimyilmaz


People also ask

How do I create URL patterns in Django?

import views urlpatterns = [ path('blog/', views. page), path('blog/page<int:num>/', views. page), ] # View (in blog/views.py) def page(request, num=1): # Output the appropriate page of blog entries, according to num. ... In the above example, both URL patterns point to the same view – views.

What is dynamic URL in Django?

Being able to capture one or more values from a given URL during an HTTP request is an important feature Django offers developers. We already saw a little bit about how Django routing works, but those examples used hard-coded URL patterns. While this does work, it does not scale.

How does Django treat a request URL string?

How does Django treat a request URL string? Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).


2 Answers

Django uses regular expressions to match incoming requests. In python a dot (.) matches any character except a newline. See docs for more information and try:

(r'^checkstring/(?P<string>.+)/$',views.check_str,name='check str')

Also keep in mind that this will accept any character (including the forward slash) which may not be desirable for you. Be sure to test to make sure everything works as you would expect.

like image 185
garnertb Avatar answered Nov 03 '22 00:11

garnertb


In Django >= 2.0, you can implement in the following way.

from django.urls import path

urlpatterns = [
    ...
    path('polls/<string>/$','polls.views.detail')
    ...
]
like image 33
SuperNova Avatar answered Nov 03 '22 00:11

SuperNova