Extra space showing in end url - django-views

I am having an issue with Panda. I am trying to add a new views to my website and when I type this line in the product/urls.py file I get an error stating that the endpoint was not found by Panda - Page not found (http://127.0.0.1:8000/products/new/)
Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order:
admin/
products/
products/ new
The current path, products/new/, didn't match any of these.
I have created a new function to hold the new products view
def new(request):
return HttpResponse('New Product')
Then I have mapped the endpoint in the products/urls.py file
urlpatterns = [
path('', views.index),
**path('new', views.new)**
]
P.S. The index is behaving as expected

The space is just formatting to show that these is a set of suburls. The problem is the trailing slash:
urlpatterns = [
path('', views.index),
path('new/', views.new)
]

Related

How to write a urls.py in django so that I can do something like */page

Here is the problem:
I have an app with the following models: project, position, outreach
A position is connected to a project and project only with a Foreign key
An outreach is connected to a position and a position only with a Foreign key
I can create a new project from almost anywhere in my app (same for the other objects). Currently I wrote that a new project is created from the url dashboard/newjobproject but I would to make it so that depending on the page that I am, the url simply becomes something like www.myapp.com/..../newproject
What's a way to write the urls.py to achieve that?
from django.urls import path
from action import views
app_name = 'action'
urlpatterns = [
# ex: /action/
path('', views.login, name='login'),
path('dashboard/', views.dashboard, name='dashboard'),
path('contacts/', views.contacts, name='contacts'),
path('projects/', views.project, name='project'),
path('contacts/newcontact', views.new_contact, name='new_contact'),
path('projects/newjobproject', views.new_outreach, name='new_outreach'),
path('dashboard/newjobproject', views.new_jobproject, name='new_jobproject'),
path('projects/<uuid>/newjobposition', views.new_jobposition, name='new_jobposition'),
]
However,
Try adding this to the bottom of urlpatterns:
path('<path:p>/newjobproject', views.new_jobproject, name='whatever-name-you-want'),
and in your views.py:
def new_jobproject(request, p):
Tbh though, this is sort of a hacky way to do it. It'll break in a few locations. If you have a main urlpatterns array in which you're including the urls for this 'action' app as APIs, this solution won't work outside the API urls.
For eg. if you have:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include('action.urls')),
]
And you access your url like this -> www.myapp.com/api/v1/....../newjobproject, then the code will work. If you try to access www.myapp.com/..../newjobproject or www.myapp.com/admin/..../newjobproject then the code will break and it will not match any of the paths. I'm not sure how you'd get it to work in that case.
If the above scenario is not an issue, if you're not going to be using these views as APIs, and your urlpatterns looks something like this:
urlpatterns = [
path('admin', admin.site.urls),
path('/', include('action.urls')),
]
then the code should work for all urls except for the admin/.../newjobproject case.

Router not displaying correct URL in Django RestFramework?

This is how I defined urls.py file of my app
router = DefaultRouter()
router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset')
router.register('profiles', views.UserProfileViewSet)
router.register('schema', views.SchemaViewSet)
router.register('creddefination', views.CredDefViewSet)
router.register('overalltable', views.OverallViewSet)
urlpatterns = [
path('', include(router.urls)),
]
urls.py of Project:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('DIAPI.urls')),
]
I am not getting correct address for creddefination. But when i manually go to http://127.0.0.1:7000/api/creddefination/ it is working. It is just not displaying correctly. What might be reason for this
I guess views.CredDefViewSet and views.OverallViewSet are using the same model.
If that's true, then the default register's basename will be named after that model and used as name in a call to Django's reverse url construction. Since the API Root view will be trying to resolve both views with the same name, it'll lead to the same url.
Workaround is to explicitly add a basename to one of the view:
router.register('creddefination', views.CredDefViewSet, basename='creddeef')

Django url/route order not maintained

I have the following in my root URLconf module (there's more, but not important, so left out):
urlpatterns = [
re_path(r'^password-reset-redirect-view/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
password_reset_redirect,
name = 'password_reset_confirm'),
path('', include('search.urls')),
path('', include('customer_portal.urls')),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
Here's the customer_portal.urls:
urlpatterns = [
path('customer/contact/', views.contact),
path('', views.home),
re_path(r"^confirm-email/(?P<key>[-:\w]+)/$", views.email_verification,
name="account_confirm_email"),
]
Here's the rest_auth.registration.urls:
urlpatterns = [
url(r'^$', RegisterView.as_view(), name='rest_register'),
url(r'^verify-email/$', VerifyEmailView.as_view(), name='rest_verify_email'),
url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(),
name='account_confirm_email'),
]
As you can see both included urls.py urlpatterns have a view named 'account_confirm_email'.
Somewhere in the code this is ran:
url = reverse(
"account_confirm_email",
args=[emailconfirmation.key])
Since customer_portal.urls is included before rest_auth.registration.urls, I expect the route account_confirm_email in customer_portal.urls to be returned by the above reverse method. But instead I get the rest_auth.registration.urls route URL.
Just to be sure I commented out the route in rest_auth.registration.urls, and then I did get the correct URL (customer_portal URL) returned.
It is filled into an email, I check that email and see that I have the wanted url: http://127.0.0.1:8000/confirm-email/......./, instead of: http://127.0.0.1:8000/rest-auth/registration/account-confirm-email/...../
Can anyone tell me why the customer_portal URL isn't the one being reversed in both cases?
Django docs say:
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.

Django URL regex with variables

Was hoping someone could point me in the right direction with this. I've tried nearly everything I can think of, but I can't seem to get it to work. I've got a set of URLs I'd like to match in Django:
www.something.com/django/tabs/
www.something.com/django/tabs/?id=1
Basically, I want to make it so that when you just visit www.something.com/django/tabs/ it takes you to a splash page where you can browse through stuff. When you visit the second URL however, it takes you to a specific page which you can browse to from the first URL. This page is rendered based on an object in the database, which is why the id number is there. I've tried to account for this in the URL regex, but nothing I try seems to work. They all just take me to the main page.
This is what I have in urls.py within the main site folder:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^tabs/', include("tabs.urls")),
]
and within urls.py in the app's folder:
urlpatterns = [
url(r'\?id=\d+$', tab),
url(r'^$', alltabs)
]
Would anyone be so kind as to point me in the right direction? Thanks in advance!
You are not following the right approach here. Query paramers are used to change the behaviour of the page slightly. Like a added filter, search query etc.
What i would suggest is you have only one view and render different templates based on query parameters in the view.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^tabs/', alltabs),
]
In your alltab views you can have something like this.
def alltabs(request):
if request.GET.get("id"):
id = request.GET.get("id")
your_object = MyModel.objects.get(id=id)
return render_to_response("tab.html", {"object":your_object})
return render_to_response("alltab.html")
Hope this helps
This is not the preferred 'django way' of defining urls patterns, I would say:-)
In the spirit of django would be something like
www.something.com/django/tabs/
www.something.com/django/tabs/1/
....
www.something.com/django/tabs/4/
and for this you define your url patterns within the app for example this way
tabs/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /tabs/
url(r'^$', views.index, name='index'),
# ex: /tabs/5/
url(r'^(?P<tab_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /tabs/5/results/
url(r'^(?P<tab_id>[0-9]+)/results/$', views.results, name='results'),
]
and something similar in your views
tabs/views.py:
from django.shortcuts import get_object_or_404, render
from tabs.models import Tab
def index(request):
return render(request, 'tabs/index.html')
def detail(request, tab_id):
tab = get_object_or_404(Tab, pk=tab_id)
return render(request, 'tabs/detail.html', {'tab': tab})
...
You can follow this django tutorial for more details:

Not able to add url in Django router

I am not able to add workers URL which is pointing to a method in views.py. In below urls.py configuration, I had created a DefaultRouter, and registered 6 URLs. First 5 are working good(They are Class Based Views), however the last URL(workers, which is method based view) is not working. This URL is not matched with any of the URLs listed in url.conf. Error message I am getting 'Using the URLconf defined in maidFactory.urls, Django tried these URL patterns, in this order:. . . . . . .The current URL, workers/, didn't match any of these.'
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'slots', views.SlotViewSet)
router.register(r'city', views.CityViewSet)
router.register(r'location',views.LocationViewSet,base_name='locationMy')
router.register(r'workers',views.WorkerViewSet,base_name='getWorkersBySlotAndLocation')
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
#url(r'^', include('maidFactory.api.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^auth/', include('rest_framework_social_oauth2.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))]
My method based view is as follows:
def WorkerViewSet(request):
cursor = connection.cursor()
#cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
cursor.execute("select p.wid,p.fname, a.description from workerProfile as p, workerAccount as a where a.isactive=1 and a.wid=p.wid")
row = cursor.fetchone()
return HttpResponse(row)
Your WorkerViewSet is not a actual DRF ViewSet but a Django function-based view returning Django HttpResponse.
You should convert it to a proper DRF viewset and then register your router with this viewset.
Another option is to add this as a url in urlpatterns in your urls file and it should work perfectly.
urlpatterns = [
url(r'^my/url/path/$', my_views.WorkerViewSet), # This will work
....
]