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
Related
I'm using an App that configures some Admin URLs as:
#admin.py....
def get_urls(self):
urls = super(FormAdmin, self).get_urls()
extra_urls = [
url("^(?P<form_id>\d+)/entries/$",
self.admin_site.admin_view(self.entries_view),
name="form_entries"),
#......
]
return extra_urls + urls
I'm having trouble using template tags to get a URL corresponding to that, in one of my templates. I'm trying stuff like:
4-Entries
(Where forms is the App's label). I keep running into the No Reverse Match type of errors:
NoReverseMatch at /polls/ Reverse for 'forms_form_entries' with
arguments '(4,)' and keyword arguments '{}' not found. 0 pattern(s)
tried: []
What am I missing that makes the tag work correctly?
Try this in html
4-Entries
Your url pattern name form_entries doesn't match forms_form_entries from the URL tag. Django does not automatically prefix the pattern name with <app_name>_ as you appear to be expecting.
Change one of them so that they match.
I am trying to redirect users to a create-profile form after signup.Since I don't know how to use dynamic url for LOGIN_REDIRECT_URL.I tried this little trick of linking it to a static view then finally to a dynamic view using redirect.It gives the error Reverse for 'add_profile' with arguments '()' and keyword arguments '{'username': u'badguy'}' not found. 0 pattern(s) tried: [] (with 'badguy' truly the username of the just signed-up user').From the error,it is clearly passing the username to the view.My codes are:
settings.py
LOGIN_REDIRECT_URL = '/prof-change/gdyu734648dgey83y37gyyeyu8g/'
urls.py
url(r'^prof-change/gdyu734648dgey83y37gyyeyu8g/',views.login_redir,name='login_redir'),
url(r'^create-profile/(?P<username>\w+)/$',views.add_profile,name='create-profile'),
views.py
def login_redir(request):
user=get_object_or_404(User,username=request.user.username)
username=user.username
return redirect('add_profile',username=username)
def add_profile(request,username):
userman=User.objects.get(username=username)
........
........
When you reverse urls (including when you use a url name with the redirect shortcut), you should use the name of the url pattern, not the view. The url pattern has name='create-profile', so use that.
redirect('create-profile', username=username)
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.
Django 1.8 / Python 3.4
I have a website.html that displays entries from my database, each of which is identified by its ID. Now, at the end of each displayed entry I have a link to an "edit" view, looking like this:
<td>edit</td>
The link is working fine and leads to the correct view:
def edit(request, object_id):
implemented in views.py. There some code is executed correctly too, and in the view's last line I have:
return redirect('website.html')
Obviously, after the chosen entry has been edited I want my website.html with the edited entry being displayed in the browser again: 127.0.0.1:8000/website/. However, what happens is that I get a Page not found (404) error, with the information:
Requested URL 127.0.0.1:8000/website/2/website.html
The "2" here is the ID of the entry.
Maybe I have the wrong idea about how redirects work, but I was assuming that instead of calling the respective view's url from url.py it would open the url provided in the redirect() function?!
What happens, though, is that this url gets appended to the view's url!
Here is my urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from www.list.views import website, edit
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^website/$', website, name="website"),
url(r'^website/(?P<object_id>\d+)/$', edit, name="edit"),
]
I'm pretty sure the third url entry is causing the problem but I have absolutely no idea how to change it for the redirect to work. Also, the edit view doesn't have an actual website (template), but I'm supposed to provide a URL for it, so this was the best I could think of.
The way this should work is: Click the "edit" link on website.html, the code from the edit-view is being executed, and, afterwards, the website.html with the change in the database entry gets displayed again.
^^ How to achieve this? Any help is appreciated!
Redirect uses names or absolute URLS. You should either use the name of your URL:
return redirect('website') # since name="website"
or an absolute URL, like:
return redirect('/website/')
you can use the reverse function instead of redirect
from django.core.urlresolvers import reverse
return reverse('website')
I found the mistake and the solution:
At the end of the edit-view it's correct to write "return redirect('website')". However, just as I assumed, the URL of edit in urls.py was wrong.
Instead of
url(r'^website/(?P<object_id>\d+)/$', edit, name="edit"),
it should just be
url(r'^(?P<object_id>\d+)/$', edit, name="edit"),
Thank you nonetheless!
I have an app which serves two purposes - displays members and centres of my company. They both work exactly the same, save a different variable when filtering my model. Problem is I can't get the current url onto the template to use in my custom breadcrumbs.
I have this urlpattern in my main urls.py:
# --- urls.py ----
url(r'^find-member/', include('company.directory.urls'), \
{'which_app': 'members'}, name='find_member'),
url(r'^find-centre/', include('company.directory.urls'), \
{'which_app': 'training'}, name='find_centre'),
of which links to my app urls.py:
# ---- company/urls.py ----
from django.conf.urls.defaults import *
urlpatterns = patterns('company.directory.views',
url(r'^$', 'index'),
url(r'^(?P<slug>\w+)/$', 'index'),
)
on my template I wish to create a link to the first urlpatten for use with my custom breadcrumbs
<a href='/find-member/'>members</a>
or
<a href='/find-centre/'>Centre</a>
based upon which url I'm using the app with.
my view looks like this:
# ---- company/view.py ----
def index(request, which_app=None, slug=None):
#r = reverse('' ,kwargs={'which_app'=training )
s = "%s %s" % (which_app, slug)
return render_to_response('directory/index.html', locals())
I would like to find the url based upon the which_app variable passed into the def.
I can't seem to use resolve() or reverse(). I'm probably doing it wrong. I haven't really got a template to show right now.
Does anybody have any suggestions? I'd love some advice.
Thanks in advance.
You don't need to use a function. Your view is passed the request object, which has an attribute path which is the path that was called. See the request docs.