how can two URL point to the same function, one with parameter and one without, both should show the index page, second one pass a parameter?
But the second one is incorrect, it gives me an error when i try to pass a parameter.
(r'^$', 'index'),
(r'^/(?P<jobtype>.*)/$', 'index'),
Thanks in Advance
the whole url :
urlpatterns+= patterns('job.views',
url(r'^$', 'index'),
(r'/(?P<jobtype>.*)/$', 'index'),
(r'^profile/addJob/$', 'addJob'),
(r'editjob/(?P<jobid>.*)/$', 'editJob'),
)
the error is
Page not found (404)
Request Method: GET
Request URL: 127.0.0.1:8000/reng%C3%B8ring/
I try to pass a string paramter "rengøring"
You can make the jobtype parameter of the index view optional:
def index(request, jobtype=None):
...
if jobtype is not None:
do_something()
...
return render_to_response('index.html', locals())
Related
In my App I have the file urls.py that contains these rows:
...
path('home/', views.home, name='home'),
path('page/', views.page, name='page'),
....
and in my view.py file i have two view like this:
def home(request, value=0):
print("value=", value)
return render(request, 'template.html', context)
def page(request):
if bad:
return redirect(reverse('home'), value=1)
Is it possible to have the view function with a parameter (like the value in this case) and then use redirection from the page view passing some value based on the same condition like value=1, in this case, using the format described in the urls.py?
The code above always prints value=0 no matter what.
The only way I can think to do this is to use global variables which I would really like to avoid...
Yes, but you need to add the parameter to the URL:
path('home/', views.home, name='home1'),
path('home/<int:value>/', views.home, name='home2'),
Then you need to pass the page in the redirect itself, together with the name of the view, you should not use reverse(..) here:
def page(request):
if bad:
return redirect('home2', value=1)
I have two apps in my django project "card" and "blog"
my project urls.py is :
urlpatterns = [
path('admin/', admin.site.urls),
path(r'', include(card.urls)),
path('', include('blog.urls')),]
url.py for "card" app is:
urlpatterns = [
re_path(r'^card/$', views.cardindex, name='cardindex'),
re_path(r'^(?P<card_url_var>[-\w.]+)/$', views.carddet, name='carddetail'),]
views.py for "card" app is:
def cardindex(request):
....
def carddet(request, card_url_var):
try:
url_carddetails = carddata.objects.get(page_end_url=card_url_var)
except carddata.DoesNotExist:
raise Http404("Card you are looking for, does not exists")
return render(request, 'card.html', {'url_carddetails':url_carddetails})
Now urls.py for "blog" apps is:
urlpatterns = [
re_path(r'^blog/$', views.articleindex, name='articleindex'),
re_path(r'^(?P<art_url_var>[-\w.]+)/$', views.articledet, name='articledetail'),]
viws.py for blog apps is:
def articleindex(request):
....
def articledet(request, art_url_var):
try:
url_articledetails = articledata.objects.get(art_end_url=art_url_var)
except articledata.DoesNotExist:
raise Http404("Article you are looking for, does not exists")
return render(request, 'article.html', {'url_articledetails':url_articledetails})
When I request urls that are in "page_end_url" column of "carddata" model the code works fine. But when I request urls that are in "art_end_url" column of "articledata" model it returns Http404 "Card you are looking for, does not exists".
For Example:
If I request example.com/new-year-card-2018
The Code works fine because "new-year-card-2018" exists in "page_end_url" column.
But If i request example.com/best-designs-of-2018
The url "/best-design-of-2018" whis is saved "art_end_url" attribute of "articledata" model. The code returns Http404 "Card you are looking for, does not exists"
So please tell me that, is there is way to exit carddet function in "card" views.py file, if requested url i.e "card_url_var" does not match with "page_end_url".
I am a newbie in django.
Any suggestions would be helpful. Thanks in Advance
You request keeps calling the first URL matches from your URLs patterns.
Actually, these 2 URLs are almost same:
re_path(r'^(?P<card_url_var>[-\w.]+)/$', views.carddet, name='carddetail'),]
re_path(r'^(?P<art_url_var>[-\w.]+)/$', views.articledet, name='articledetail'),]
This (?P<card_url_var>[-\w.]+) is waiting for a slug : /slug-slug/
And also this (?P<art_url_var>[-\w.]+): /slug-slug/.
So Django will look for the first match URL, obviously the first will match. What you can do is add something different in each, like:
re_path(r'^card/(?P<card_url_var>[-\w.]+)/$', views.carddet, name='carddetail'),]
re_path(r'^article/(?P<art_url_var>[-\w.]+)/$', views.articledet, name='articledetail'),]
you can try in this way.
from django.core.urlresolvers import reverse
try:
...
except:
return redirect(reverse('name-of-url'))
more details here
I was reading the thread Django optional url parameters
And following the steps to generate a URL with a single optional parameter.
Well, my URL should be:
/client/
/client/?clientname=John
And I have defined two urlpatterns
url(r'^$', views.index, name='index'),
url(r'^/(?P<clientname>\d+)/',views.index),
Well, at this point both of them render the page.
But, in my view:
def index(request, clientname='noparameter'):
print("The searched name is: " + str(clientname))
The searched name is always noparameter
Am I doing something wrong?
Url you are having is
/client/John/
instead of
/client/?clientname=John
also even in the following example using John will fail as your regex is for digits , check out more on topic of django dispatcher
/client/4/
if you want to get GET parameters instead you can do that in view by using the following
request.GET.get('clientanme', None)
It seems as though you are getting confused between a keyword argument and a get request. Using keyword arguments, which your urls.py is configured for, your view would like this:
def index(request, **kwargs):
clientname = kwargs.get("clientname", "noparameter")
print("The searched name is: " + str(clientname))
Your urls.py would also have to change to this for the url to this:
url(r'^client/(?P<clientname>\w+)/',views.index),
This could be called in the browser like:
/client/John
I have 2 links in my html templates. First link pass only 1 parameter to URL and second link pass 2 parameters. Like this:
{{categ_name}}
{{subcateg_name}}
Now when i click on link with 1 parameter it works fine. I get the parameter value in my django view. But When i click on link with two parameters i only get the first parameter. I get None in the value of second parameter.
My urls.py:
urlpatterns = patterns('',
url(r'^products/(?P<categ_name>\w+)/', views.products, name='products_category'),
url(r'^products/(?P<categ_name>\w+)/(?P<subcateg_name>\w+)/', views.products, name='products_subcategory'),
url(r'^logout/',views.logoutView, name='logout'),)
My views.py:
def products(request, categ_name=None, subcateg_name=None):
print categ_name, subcateg_name
...
How to get the value of second parametre?
Change your urls to:
urlpatterns = patterns('',
url(r'^products/(?P<categ_name>\w+)/$', views.products, name='products_category'),
url(r'^products/(?P<categ_name>\w+)/(?P<subcateg_name>\w+)/$', views.products, name='products_subcategory'),
url(r'^logout/',views.logoutView, name='logout'),)
Then, you avoid your 2-parameter url being matched by the first 1-parameter pattern. The $ special character means end of string.
How to redirect with variables in django?
Please guide me, thank you.
urls.py:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^computer/$', views.computer, name='computer'),
url(r'^result/$', views.result, name='result'),
)
This is my original views.py :
def computer(request):
result = Computer.objects.order_by('?')[:1]
return render(request, 'many/result.html',{'result':result})
And I found I problem, render will not redirect to moneymany/result.html on the url,
so if the user refresh, it will get another result on the same page.
So I have to use redirect to many/result.html .
What's the usually way to redirect in django and I have to pass variable result?
I try this,but not work :
def result(request):
return render(request, 'many/result.html')
def computer(request):
result = Computer.objects.order_by('?')[:1]
url = reverse(('many:result'), kwargs={ 'result': result })
return HttpResponseRedirect(url)
you need
url(r'^result/(?P<result>[^\/]*)/$', views.result, name='result'),
and
return redirect(reverse('many:result', kwargs={ 'result': result }))
or (without changing url)
return redirect('/result/?p=%s' % result )
if you want to maintain POST data while redirecting, then it means your design isnot good. quoting Lukasz:
If you faced such problem there's slight chance that you had
over-complicated your design. This is a restriction of HTTP that POST
data cannot go with redirects.
How about using redirect.
from django.shortcuts import redirect
def computer(request):
result = Computer.objects.order_by('?')[:1]
return redirect('view-name-you-want', { 'result'=result })
this worked with i just needed to pass url parameters as arguments
return redirect('pagename' ,param1 , param2)
my url looks like :
path('page', views.somefunction, name="pagename")
Note: in my case somefunction accept only POST parameters
To redirect from a view to another view with data, you can use session with request.session['key'] and in this case, you don't need to modify path() in "myapp/urls.py" as shown below. Then, give the conbination of the app name "myapp", colon ":" and the view name "dest_view" which is set in path() in "myapp/urls.py" as shown below:
# "myapp/views.py"
from django.shortcuts import redirect
def redirect_view(request):
# Here
request.session['person'] = {'name': 'John', 'age': 27}
# Here
return redirect("myapp:dest_view")
# "myapp/urls.py"
from django.urls import path
from . import views
app_name = "myapp"
urlpatterns = [ # This is view name
path('dest/', views.destination_view, name="dest_view")
]
Then, this is how you get the data of "post" method:
# "myapp/index.html"
{{ request.session.person.name }} {# John #}
{{ request.session.person.age }} {# 27 #}