Django reverse URL issue - python

I'm having issues getting the following code (below) to work (there are no errors) . In my template I'm outputting item.get_settings_url but I get nothing. What I'm I doing wrong here?
In my models I have the following model method:
def get_settings_url(self):
return reverse('sms.views.keyword_settings', args=[str(self.keyword)])
urls:
url(r'^keyword/^(?P<keyword>[\.\w-]+)/settings/$', views.keyword_settings, name='keyword_settings')
view:
def keyword_settings(request, keyword):
return render_to_response('keyword_settings.html', context_instance=RequestContext(request))

Your URL contains a named parameter. Hence, you need to pass that name when calling reverse. Also, you should use the name of the URL to make the reverse lookup short and easier to maintain:
return reverse('keyword_settings', kwargs={'keyword': str(self.keyword)})

Related

Issue on Django Url Routers

I an trying to make url router in Django which supports following URLs :
http://localhost:8000/location/configuration
http://localhost:8000/location/d3d710fcfc1391b0a8182239881b8bf7/configuration
url(r'^locations/configuration$',
location_config.as_view(), name="location-config"),
url(r'^locations/(?P<location_key>[\w]+)/configuration$',
location_config.as_view(), name="location-config-uri")
Whenever I tried to hit http://localhost:8000/location/configuration, it picked up the second URL routing format instead of picking up first one.
Error:
TypeError at /locations/configuration/ get() missing 1 required
positional argument: 'location_key'
Can anyone help me here what goes wrong with the url routing format?
Nope, it does pick the first pattern which has no arguments, however you're using the same view in both patterns and location_config view has required argument location_key which is not provided when first pattern matches the URL. That's what error message is saying.
So write another view which will not require location_key argument or alter this view definition: add default to the parameter
def location_config(request, location_key=None):
....
now it is not a "required positional argument".
django Will look for a pk when you are using a detail view by default. you have to override it by using get_object()
in your case
def get_object(self, queryset=None):
location_key = self.kwargs.get('location_key')
obj = Model.objects.get(id=location_key)
return obj

Django pass empty parameter

I'm trying to pass an empty parameter to render a template but I can not achieve this I do not know if the problem is in urls.py or views, I really appreciate a hand.
Urls
url(r'^hola/(\b[a-z\.-]+)$', views.hola, name='hola'),
Views
def hola(request, varr = ''):
#val = val
pregunta = Datos_usuario_DB.objects.all().order_by('-id').filter(activo="1")[:15]
plantilla = {'': 'index.html', 'nosotros': 'nosotros.html'}
return render(request, plantilla['%s' % varr], {'pregunta': pregunta})
When I access to hola/ it says that the website does not exist.
If you want /hola/ to work, it's easy to add another URL pattern:
url(r'^hola/$', views.hola, name='hola'),
url(r'^hola/([a-z\.-]+)$', views.hola, name='hola'),
It's not clear to me why you have \b in the regex, so I removed it.
your urls is not contains hola/ entry, so It returns error.
If you want to call hola/, you need to add url in urls.py

Pass arguments between Webapp2 redirects

I want to redirect URL without slug, to the one with slug, at the urls.py level.
My endpoints looks as follows:
(r'/invoices/<:(-?\d+)>/print/', PrintHandler, 'ShortPrintHandler')
(r'/invoices/<:(-?\d+)>/<:([\w-]*)>/print/', PrintHandler, 'FullPrintHandler')
Is there any way I can pass first, decimal, argument from short URL to the long one, on redirect? Generating URLs without slug is already covered at handler level.
Tried to handle it with
RedirectRoute(r'/invoices/<:(-?\d+)>/print/', PrintHandler, redirect_to_name='FullPrintHandler')
But an error was thrown:
KeyError: 'Missing argument "1" to build URI.'
You can't do that with just a RedirectRoute; you need to get the slug value from somewhere.
You'll need to write a standard route, and in the handler you should get the object from the datastore and return a redirect to the full path using the slug.
Something like (untested):
class RedirectToFullPath(webapp2.RequestHandler):
def get(self, invoice_id):
invoice = Invoice.get_by_id(invoice_id)
self.redirect_to('FullPrintHandler', invoice_id, invoice.slug)

Django: URL doesn't match view function

I have my URL defined as follows:
(r'^article/edit/(.*)/$', 'mysite.views.edit_article')
And the function defined as:
def edit_article(request, article_id):
However, it seems that any request to this page results in the wrong value being passed in for article_id. If I redefine my URL as
(r'^article/(.*)/$', 'mysite.views.edit_article')
Minus the "edit/" it seems to work. Any suggestions on how to fix this?
Try this:
url (r'^article/edit/(?P<article_id>\d+)$', 'mysite.views.edit_article'),
Take a look at the Named Groups in the Django documentation

How come this Django matching doesn't work in urls.py?

(r'^signup(.*)password=goodbye$','abc.wall.views.register_goodbye'),
This doesn't work. It doesn't match! Even when I hit this:
www.mydomain.com/signup?password=goodbye
It does not match it and simply skips over it. Why?
Note: I understand this is not good practice to match the GET parameter. However, it's forced and I must do it due to code that I can't change.
URLs don't match on query parameters. They take the path (everything before the ?) from the request, and attempts to match against your URL regex.
What you need to do is handle the GET parameters in your view, and route from there to other functions if you need to. Example:
request: http://www.mydomain.com/signup/?password=goodbye
(r'^signup/$','abc.wall.views.signup_front')
def signup_front(self, request):
query_param = request.GET.get('password', None)
if query_param == "goodbye":
return signup_goodbye(request)
# other stuff here
def signup_goodbye(self, request):
# blah
# return render_to_response(..)
Because urls.py doesn't match against query parameters.

Categories