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

(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.

Related

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

How do you make a url that passes a parameter work in Django?

I'm working on registration logic and I can't seem to make the parameter pass in to work properly. The error I get is a 404 page not found. Previously, I also got a “The view didn't return an HttpResponse object" error. Any help is appreciated.
Here is my url from urls.py:
url(r'^accounts/confirm/(?P<activation_key>\d+)/$', 'mysite.views.confirm', name='confirm'),
This is my views.py:
def confirm(request, activation_key):
if request.user.is_authenticated():
HttpResponseRedirect('/home')
user = Hash.objects.filter(hash_key = activation_key)
if user:
user = Hash.objects.get(hash_key = activation_key)
user_obj = User.objects.get(username= user.username)
user_obj.is_active = True
user_obj.save()
HttpResponseRedirect('/home')
I send the url with a string that looks like:
"Click the link to activate your account http://www.example.com/accounts/confirm/%s" % (obj.username, activation_key)"
So the link looks like this:
http://www.example.com/accounts/confirm/4beo8d98fef1cd336a0f239jf4dc7fbe7bad8849a127d847f
You have two issues here:
Remove the trailing / from your pattern, or make it /? so it will be optional.
/d+ will only match digits, and your link also contains other characters. Try [a-z0-9]+ instead.
Complete pattern:
^accounts/confirm/(?P<activation_key>[a-z0-9]+)$
Remove / from end of your url:
url(r'^accounts/confirm/(?P<activation_key>\d+)$', 'mysite.views.confirm', name='confirm'),
or add / to end of your link:
http://www.example.com/accounts/confirm/4beo8d98fef1cd336a0f239jf4dc7fbe7bad8849a127d847f/

Django reverse URL issue

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)})

How to add conditional redirect to each view in Pyramid?

I'd like to check a condition before each request and call different views.
How is that achieved?
One solution I can think of is adding something to subscriber NewRequest, but I am stuck:
#subscriber(NewRequest)
def new_request_subscriber(event):
if condition:
#what now?
#subscriber(NewRequest)
def new_request_subscriber(event):
if condition:
raise pyramid.httpexceptions.HTTPFound(location=somelocation) ## to issue a proper redirect
More info can be found here:
http://pyramid.readthedocs.org/en/latest/api/httpexceptions.html#pyramid.httpexceptions.HTTPFound
Well you've given very little information about the "condition" or what you mean by "call different views", so I'll assume you do not want to invoke a redirect but instead you want the application to think a different URL is being requested. To do that you can look at pyramid_rewrite, which is pretty handy for these things, or you can just change the request's path within the NewRequest subscriber, since it is invoked before Pyramid dispatches to a view.
if request.path == '/foo':
request.path = '/bar':
config.add_route('foo', '/foo') # never matches
config.add_route('bar', '/bar')
Yet another option to "check a condition ... and call different views" is to use custom view predicates
From Cris McDonough's blog post:
def example_dot_com_host(info, request):
if request.host == 'www.example.com:
return True
That's a custom predicate there. It returns True if the hostname is www.example.com. Here's how we use it:
#view_config(route_name='blogentry', request_method='GET')
def get_blogentry(request):
...
#view_config(route_name='blogentry', request_method='POST')
def post_blogentry(request):
...
#view_config(route_name='blogentry', request_method='GET',
custom_predicates=(example_dot_com_host,))
def get_blogentry_example_com(request):
...
#view_config(route_name='blogentry', request_method='POST',
custom_predicates=(example_dot_com_host,))
def post_blogentry_example_com(request):
...
However, for your particular problem (display a sign in page if user has no permission to view the page) a better way to achieve this would be to set up permissions for views so the framework raises an exception when user has no permission, and then register a custom view for that exception which will show a sign in form.

Django middleware process_template_response method not being called

I have the following middleware class:
class CommonContextMiddleware:
def process_template_response(self, request, response):
# Get the context and top videos
context = response.context_data
...
# Add most_recent and most_viewed to the context...
context['most_recent'] = top_videos['most_recent'][:3]
context['most_viewed'] = top_videos['most_viewed'][:3]
# ...then continue rendering
return response
However, no matter what I put in the function, it's never being called. I presumed that this method would be called for every single template response generated, am I wrong?
Thanks in advance.
I assume when you're talking about "template response", you are actually returning a TemplateResponse from your Django view?
This isn't really the best place for this sort of thing. If you just want to add variables into every template context, the best place to do it is in a context processor.

Categories