Issue with Flask Dynamic Routing - flask

I wanted to make a 404 page on flask that is able to display on the page whatever the user put in the search bar to create the 404 page. Here is the code I have
#app.errorhandler(404)
def user(name):
return "<h1>This is a page for {}</h1>". format(name)
Yet when I run this code it displays "This is a page for 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." on the page. How would I make it show whatever the user put in the url.

Related

Moved legacy classic asp web site to django app but having trouble with django URL redirect app - old URLs with parameters get 500 error

I moved a 20 year old classic asp web site to a django app recently. Google Search Console is showing 500 errors for tons of very old URLS with parameters like /somefile.asp?ID=1234&name=some-name. Most of these URLS I don't even care about - they are really old but would rather they result in 404 than 500. Some do relate to newer content and in theory I could redirect to new django pages but when I try to redirect them using the django redirect app, the site shows 500 errors - like the ? either stops the pages from ever getting to the redirect middleware or the redirect app doesn't like the "?". How can I redirect these urls so I don't get 500 errors? Is there a way in a view to say:
if the full url path is x
redirect to full url path y
I have looked all over stack overflow and elsewhere and can't find this exact problem or a way to write a view like this. I did try the solution here (exactly) because it seems closest to my issue, but it did not work for me for this exact problem: Django's redirects app doesn't work with URL parameters
An example would be /profiles/?adid=134&v=857
The error with debug true is:
DoesNotExist at /profiles/
BusinessCategory matching query does not exist....
So it is trying to match this URL:
path('<slug:slug>/', views.view_category_list, name='view_category_list'),
before it ever gets to the /?
Relevant view code:
def view_category_list(request, slug):
try:
category_detail = BusinessCategory.objects.get(slug=slug)
except BusinessCategory.DoesNotExist:
category_detail = None
if category_detail:
--code here is all working fine so removed it to get to the issue--
else:
raise Http404
I hoped raising the 404 would call up the redirect app to do its job at redirecting to a specific url but it doesn't - it just shows the custom 404 when debug is False. Anyway, the 404 is better than the 500 for SEO purposes but I still would prefer being able to actually redirect some of the URLs to relevant content.

Accessing URL in 'get' method of view

I want a web page (with the url page3) to be displayed differently depending on whether a user on my website is redirected to it from the pages with urls page1 or page2.
How can I access the full url (not just the query parametres in it) from which the user was redirected in the get method in the view associated with the url page3 ?
After reading the docs more thoroughly (thanks for the tip Brandon!), I found request.META['HTTP_REFERER'] did the trick.

Check whether a page exists in Django CMS

I am creating a page in the admin area of Django CMS and I have the redirect field under Advanced Settings. How can I check that the URL entered in that field is a valid URL of an existing Django CMS page?
What should I test? I thought about issuing a request to that URL and if it throws a 404, then invalidate the field, but this sounds a bit too far fetched. What other options do I have?
You can check if your actual page is in a pool of pages
if your page is on the draft mode:
from cms.models import Page
your_page.get_path() in [p.get_path() for p in Page.objects.public().published()]
with a reverse_id:
your_page.get_path() in [p.get_path() for p in Page.objects.all() if p.reverse_id != your_page.reverse_id]
I've used get_page_queryset_from_path from cms.utils.page_resolver and checked that the path entered on the redirect field actually returns a valid Page using the above function.

Django redirect behavior with back button

I'm running into an issue now where I have a "random" link on my site to see a random user. The way I have it set up is to get the user_id and then use redirect to serve the proper page. The issue I'm running into is if I click the random button multiple times, clicking on back will bring me back to the page before the "random" clicks.
To be more concrete, this is what's happening:
HomePage, Click Random (go to /user1/), Click Random (go to /user4/), Hit back (end up on HomePage). In this scenario I'd like to end up on /user1/
This is the random view method:
def Random(request):
user = helpers.GetRandomUser()
return redirect('user_display', user_slug=user.username)
The template just has a link to /random/ which gets routed to the above view.
Edit: Apparently it works as expected in Firefox but in Chrome. I'd like it to have the Firefox-like behavior everywhere.
So if I understand you correctly you click two times on a link to the same url (like /random_user/) and you respond with a random redirect. This seems quite unconventional and it doesn't sound so wrong that Chrome might view this as a single history entry.
To archieve your wanted behaviour across browsers simply generate the random url before you render your random user link.
As you want to use it in multiple views, write a custom template tag:
#register.simple_tag
def random_user_url():
user_url = # generate your random user url
return user_url
In your template:
{% load your_tag_lib %}
Random user
This way every click leads the browser to a different url and will be memorized as seperate history entry.
Use the following code to force the browser not to cache the page. So, clicking back button sends request to server and now you can catch it and redirect him to the desired page.
from django.views.decorators.cache import cache_control
#cache_control(no_cache=True, must_revalidate=True)
def func()
#some code
return
To be clear, when you say "Back Button" do you mean:
Browser Back Button
Your own creation of a Back Button
If 2, are you doing this via client side? Such as via javascript?

How to redirect to page which has GET parameters after login using the {{next}} variable in django

I am using allauth to provide registration and login in my django site. Everything else seems to be working fine other than that I am having problems to redirect the person to the current page after login.
I have a page where I have some interview questions and a typical url for it would be like
/questions/?company=google
This page contains a list of questions for the company google, but to view the answer the person needs to login. The answers are displayed in a dropdown box. However when the user clicks on login a request is sent to the login page as follows
/login/?next=/questions/
And the get parameter which was actually there in my actual page is not sent because of the & in my url. How can I solve this problem. It does not look nice that the person is redirected to a different page from where he/she tried to login.
I know sending the next parameter as a GET variable is not the solution, but is there a way I can send the redirect link as a POST variable from the template.
I tried another thing, in my view that displays the questions list. I set session variables which contains the url of the current link . If a user clicks on login, in my login view I check for this particular session variable. If it is set then I redirect to that page.
However the session variable is not received in the login view, I am not sure but I think the session is reset when the user goes to the login view.
Any suggestions are appreciated.
Have you tried
next = request.get_full_path()
This will return correct path with all queries ( see docs ) , you can then pass it as GET param to redirect url e.g.
full_path = request.get_full_path()
return HttpResponseRedirect('%s?next=%s' % (reverse('login'), full_path))
You should encode the URL-parameter in this case. You want to send a variable like /questions/?company=google, but as you mentioned the ?, = (amongst others) characters are special ones. It has a special meaning when embedded in the URL. If you encode the variable with URL encoding, it becomes %2Fquestions%2F%3Fcompany%3Dgoogle. If you assign that to the parameter next, the URL becomes: /login/?next=%2Fquestions%2F%3Fcompany%3Dgoogle. This should redirect to the correct place on login.