same url pattern with differnet views and names - django

My code is below
template looks like this
<td><button> Test</button></td>
<td><button> Delete</button></td>
url patterns
urlpatterns = [
path('<int:id>/', views.confighome, name='config'),
path('<str:schmid>/', views.deleteschema, name='deleteschema'),
path('te<str:schmid>/', views.testschema, name='testschema')
]
views.py
def deleteschema(request,schmid):
some code
return redirect('/configuration/'+str(request.session["project_id"]))
def testschema(request,schmid):
some code
return redirect('/configuration/'+str(request.session["project_id"]))
Whenever I click on the Testbutton its actually calling the delete function
Any idea why this happening Since I used named url parameters
Thanks in advance

The url will always match the second path(..), since each string that starts with te is a string. You therefore better make the URLs non-overlapping, as in that no URL that matches the second path(..) can match the third path(..). Regardless what URL the {% url 'testschema' allschema.schema_name %} thus generates, if the browser sends a request with that URL, it will be matched by the second path(..).
For example:
urlpatterns = [
path('<int:id>/', views.confighome, name='config'),
path('de<str:schmid>/', views.deleteschema, name='deleteschema'),
path('te<str:schmid>/', views.testschema, name='testschema')
]
or perhaps more convenient:
urlpatterns = [
path('<int:id>/', views.confighome, name='config'),
path('<str:schmid>/delete/', views.deleteschema, name='deleteschema'),
path('<str:schmid>/test/', views.testschema, name='testschema')
]

Related

The current path,didn't match any of these

I have this in urls.py
urlpatterns = [
path("product/<str:title>/<slug:pname>/<uuid:puid>",views.viewProduct),
]
But when I try to click on the url. I got this error.
The current path, product/amazon/home-secure-snake-shield-natural-snake-r/B0882NKXW7, didn't match any of these.
Here I just want the puid but to match the pattern of URL I added str:title and str:pname
I don't want the title and pname. But my URL patern is like this-
product/store_name/product_name_slug/product_id
The B0882NKXW7 is not a valid format for a UUID [wiki]. Indeed, a UUID is typically represented as 16 octets. For example 2707820f-5182-407d-9c07-ff7845807d4c is a UUID.
You can either define your own path converter [Django-doc] to accept your product id, or you can make use of str::
urlpatterns = [
path('product/<str:title>/<slug:pname>/<str:puid>', views.viewProduct),
]
I replace the URL path
urlpatterns = [
path("product/<str:title>/<slug:pname>/<str:puid>",views.viewProduct),
]

How can I use a catch all route using `path` or `re_path` so that Django passes all unmatched requests to my index view?

My url patterns look like this:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
re_path('.*', IndexView.as_view()),
]
This works but it matches all URLs, including those prefixed with admin and api. I want those URLs to still match, and for any unmatched URLs to render IndexView.
Before 2.0 I used this regex for this purpose. I tried using it in re_path but that didn't work, which is what led me to trying the above.
url(r'^(?P<path>.*)/$', HtmlView.as_view())
Use case is a SPA where I handle 404s client side.
Many thanks in advance.
You can use two entries (one for '/', another one for anything else), but using path for both of them, which should be (slightly) more efficient:
urlpatterns = [
path('', IndexView.as_view(), {'resource': ''}),
path('<path:resource>', IndexView.as_view())
]
In this case, I'm using <path:resource> because path catches all resource names, inluding that with / in them. But it does not capture the main index resource, /. That's why the first entry. The dictionary as last argument for it is because we need to provide a resource parameter if we want to use the same view than in the second entry.
That view, of course, should have 'resource' as a paremeter:
def as_view(request, resource):
...
So as I said in the question description, trying the regex I was using before Django 2.0 in re_path did not work. It would basically match for all requests except / (i.e., index path). I fixed this by using both that regex and a second path matching / specifically. Here's the code:
urlpatterns = [
re_path(r'^(?P<path>.*)/$', IndexView.as_view()),
path('', IndexView.as_view()),
]
With these changes my other routes would match and these two routes would account for all other urls.
One Idea to go about this is let the django catch 404.
url.py
from django.conf.urls import handler404
handler404 = 'app_name.views.bad_request'
and in your views.py
views.py
def bad_request(request):
return redirect(reverse('home'))
You can always do some regex thingy to catch unmatched urls. but hey this gets the job done. :)

Django urls space gets added after main url

I get this error message
Using the URLconf defined in esarcrm.urls, Django tried these URL patterns, in this order:
1. ^person/ duplicate_check/(?P<entity>)/(?P<full_name>)/?$
2. ^admin/
3. ^api/v1/
4. ^api/v1/authenticate/$ [name='api_authenticate']
5. ^static\/(?P<path>.*)$
6. ^media\/(?P<path>.*)$
The current path, person/duplicate_check/candidate/tom, didn't match any of these.
Please not the space here 1. ^person/[SPACE]duplicate_check
my project/urls.py
urlpatterns = [
url(r'^person/', include('person.urls')),
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/authenticate/$', crm_views.ApiAuthenticateView.as_view(), name='api_authenticate'),
]
my app.urls
urlpatterns = [
url(r'duplicate_check/(?P<entity>)/(?P<full_name>)/?$', views.check_if_exist),
]
my app.views
#api_view(['GET'])
def check_if_exist(request, entity, first_name):
if entity == 'candidate':
candidates = person_models.Candidate.objects.filter(first_name=first_name)
serializer = person_serializers.CandidateMiniSerializer(candidates, many=True)
return Response(serializer.data)
What exactly am I missing?
There is no space, that's just how Django prints the URLs.
The problem has nothing to do with spaces, but with your URL. "duplicate_check" is included under person/, but you are trying to access p_check/....
Edit There are actually bigger problems with your URL pattern. You haven't actually given the capturing groups anything to capture. You need some kind of pattern inside the parentheses. Something like:
r'^duplicate_check/(?P<entity>\w+)/(?P<full_name>\w+)/?$'
which will capture all alphanumeric characters for entity and full_name.

How to go to a different page from current in Django template

urlpatterns = [
url(r'^$', predict_views.index, name = 'HomePage'),
url(r'^admin/', admin.site.urls),
url(r'^Update_db/$', predict_views.Update_db, name = 'Update_db'),
url(r'^compare/(?P<phone1_id>[0-9]+)/(?P<phone2_id>[0-9]+)/$',predict_views.Compare, name = 'Compare'),
url(r'^predict/(?P<phone_id>[0-9]+)/$',predict_views.Predict, name = 'Predict'),
]
these are my url patterns in djano. I want to go to compare directly from predict which is not possible for me currently because :
when I go to predict the url is 127.0.0.1:8000/predict/1 now when i go to compare from predict the url becomes 127.0.0.1:8000/predict/1/compare/1/2 which is not the expected url .. my url should be 127.0.0.1:8000/compare/1/2
I have seen django docs there are some redirect methods but I do not understand them.
Any help is appreciated.
Something tells me you are accidentally using relative urls. In your template, try the following:
Compare Page

Django url regexp not working

I'm trying to get my head around regexp in Django urls. I'm currently developing locally and I want to be able to direct a request such as http://localhost:8000/options/items/item-string-1121/ to the 'details' view in my app called 'options', passing in the final number part of the request string (1121) as a parameter 'id' to the view function.
The signature for details in options/views.py is as follows, taking id=1 as default:
def details(request, id=1):
...
I have the following in my root urls.py:
...
urlpatterns += patterns('',
url(r'^options/, include(options.urls')),
)
and in options/urls.py:
urlpatterns = patterns('options.views',
url(r'^items/(.+)(P<id>\d+)/$', 'details'),
...
)
Now when I try to request the above URL the dev server says it tried to match against the pattern ^options/ ^items/(.+)(P<id>\d+)/$ but it doesn't match.
Can anyone see the problem?
You need a non-greedy quantifier on the (.+), so r'^items/(.+?)(P\d+)/$'. Otherwise that first glob happily eats until the end of the string, preventing the ID from ever matching.
You are missing quotes.
urlpatterns += patterns('',
url(r'^options/, include(options.urls')),
)
Should be
urlpatterns += patterns('',
url(r'^options/', include('options.urls')),
)
I'm not too sure of your expression, might try this:
urlpatterns = patterns('options.views',
url(r'^items/(?<=-)(?P<id>\d+)/$', 'details'),
...
)