Django - Retrieve url origin from view - multiple urls to 1 view - django

I have several urls mapping to one view. Inside the url, I would like to know the url origin? It is to avoid writing multiple views (DRY).
urlpatterns = [
path('path1/', views.IndexView.as_view(), name='index'),
path('path2/', views.IndexView.as_view(), name='index')
]
class IndexView(generic.ListView):
url_origin = ... #would like path1 or path2
I looked for 'reverse' but it does not seem to be a solution to my problem. It returns an error.
reverse('index')
Thank you in advance

You can obtain the original path with request.path [Django-doc] (so in a view function for a class-based view, you can access this with self.request.path.
You can however fix this, for example by providing an extra parameter, like:
urlpatterns = [
path('path1/', views.IndexView.as_view(), name='index1', kwargs={'through': 'path1'}),
path('path2/', views.IndexView.as_view(), name='index2', kwargs={'through': 'path2'})
]
Then you can inspect the self.kwargs['through'] parameter in your class-based view.
Note that you better give the different paths a different name, since otherwise, it will indeed raise an error. By giving these as name 'index1' and 'index2', you can simply use reverse('index1'), and it is not ambiguous to what URL it should redirect.

Related

urls not overlapping -- How to fix

I am trying to filter products either by brand or category but the url path will only execute path('<slug:brand_slug>/', views.product_list,name='product_list_by_brand'), since it appears first and would not execute the second.
Is there a way I can probably merge both paths or cause both paths to work independently without taking order into consideration.
from . import views
app_name = 'shop'
urlpatterns = [
path('', views.product_list, name='product_list'),
path('<slug:brand_slug>/', views.product_list,name='product_list_by_brand'),
path('<slug:category_slug>/', views.product_list,name='product_list_by_category'),
]
Thank you in advance for your response.
the problem is your upper url pattern is overriding second URL because of same slug and some other reasons.
FIX
change your URL pattern
path('<slug:brand_slug>/brand/', views.product_list,name='product_list_by_brand'),
path('<slug:category_slug>/', views.product_list,name='product_list_by_category'),
Another Thing You Can Do!
modify your function and url pattern.
def product_list(request, slug):
mode = request.GET.get("mode")
if mode.lower() == "brand":
''' your brand code '''
pass
else:
''' your category code '''
pass
path('<slug:slug>/', views.product_list,name='product_list_by_category'),
if you want to execute brand code your URL pattern would look like this.
127.0.0.1:8000/yourslug?mode=brand
and with this url pattern it will execute category code.
127.0.0.1:8000/yourslug
so by default it will execute category code.

django url _reverse _ not a valid view function or pattern name

the redirect url is
"liveinterviewList/2"
and, ofcourse, I declare that url in url.py
more over, when I type that url in browser manualy, it works well.
what's the matter?
more question.
at this case, I write the user_id on the url.
I think, it is not good way to make url pattern.
but I don't know how I deliver the user_id variable without url pattern.
please give me a hint.
What HariHaraSudhan left out was how to use parameters. For your case, you would want something like:
path(r'liveinterviewList/<int:userId>', ..., name='live-interview'),
And then when you are ready to reverse, use this:
reverse('app:live-interview', kwargs={ 'userId': userId })
where app is the name of the app in which your view lives. If your url lives in the main urls file , you don't need the app: prefix.
Django reverse function accepts the name of the path not the URL.
lets say i have url patterns like this
urlpatterns = [
path('/users/list', name="users-list")
]
In my view i can use like this
def my_view(request):
return redirect(reverse("users-list"));
You should add a name to your path url and use it to redirect.
As the django doc says :
urls :
urlpatterns = [
path('/name', name="some-view-name")
]
def my_view(request):
...
return redirect('some-view-name')

How is the Django view class executed?

I have a simple question to ask. How is the class executed defined the views.py? For example, if I have the path defined like the following, I assume that the snippet, 'views.PostListView.as_view()', is executing the PostListView defined in the views.py. Am I right?
urlpatterns = [
path('', views.PostListView.as_view(), name='post_list'),
path('about/', views.AboutView.as_view(), name='about'),
path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'),
]
If you look at https://github.com/django/django/blob/master/django/views/generic/base.py (which is the base View class for generic views that all of your other views would generally inherit from), as_view is defined as a class/static method of the base view class, and it specifically returns a function view (def view(request, *args, **kwargs) ), which in turn takes a request object and then multipe optional args/kwargs. This view function is what gets passed to the urlpatterns. When an actual request comes in from the user, Django walks through the urlpatterns until it finds a match, and will then pass the request object and other information to the actual view function (so it gets executed once per matching request).
Hope that helps.

Url maps operation in Django

i'm new to django and i'd like to know how the url maps work in detail.
from django.conf.urls import url
from polls import views
urlpatterns =[
url(r'^$',views.index,name='index')
]
the url function takes 3 parameters, could you explain how they work and what functionalies they have.
I've searched for this, but no detailed information are available for an absolute beginner
The Django URL dispatcher contains urlpatterns which is a Python list of url() instances.
The url(regex, view, kwargs=None, name=None) function can take 4 arguments:
regex: Regular expression, pattern matching the url.
view: View name, path, function or the result of as_view() for class-based views. It can also be an include().
kwargs: Allows you to pass additional arguments to the view function or method.
name: Naming URL patterns.

django print referred url in view

In the following code how will i know there are two hyper links which are pointing to the same view.My question is in view how will i know which link the user is referring to? how can i get the referred url context in the view
JS:
window.location = "/project/server/fserver";
window.location = "/project/server/";
urls:
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^fserver/$', views.IndexView.as_view(), name='index'),
views
class IndexView(tables.DataTableView, VolumeTableMixIn):
table_class = project_tables.VolumesTable
template_name = 'project/server/index.html'
def get_data(self):
print "In get data==============="
.......
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.path
def get_data(self):
print self.request.path
...you could also do this with a single url pattern
url(r'^(?:fserver/)?$', views.IndexView.as_view(), name='index'),
or capturing as a kwarg passed to the view:
url(r'^((?P<page>fserver)/)?$', views.IndexView.as_view(), name='index'),
An Alternate way is:
-> Add a class variable in you view to store the url name:
class IndexView(tables.DataTableView, VolumeTableMixIn):
view_url_name = 'index'
........
-> Change the URL definition to following:
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^fserver/$', views.IndexView.as_view(view_url_name='index_fserver'), name='index_fserver'),
Also, this will help you get the url in more django-ish manner e.g. reverse(view_url_name)
Note: Two different urls should never be of the same name, as this creates ambiguity & After all the first matching name will be picked by Django so its of no use either.