
Quick Contact
Python Tutorial
- What is Python?
- How to Install Python?
- Python Variables and Operators
- Python Loops
- Python Functions
- Python Files
- Python Errors and Exceptions
- Python Packages
- Python Classes and Objects
- Python Strings
- PostgreSQL Data Types
- Python Generators and Decorators
- Python Dictionary
- Python Date and Time
- Python List and Tuples
- Python Multithreading and Synchronization
- Python Modules
- What is Python bytecode?
- Python Regular Expressions
Python Panda Tutorial
- Python Pandas Tutorial
- Python Pandas Features
- Advantages and Disadvantages of Python Pandas
- Pandas Library In Python
- Pandas Series To Frame
- Python Dataframeaggregate and Assign
- Pandas Dataframe Describe
- Pandas Dataframe Mean
- Pandas Hist
- Pandas Dataframe Sum
- How to convert Pandas DataFrame to Numpy array
Python Selenium
- Selenium Basics
- Selenium with Python Introduction and Installation
- Navigating links using get method Selenium Python
- Locating Single Elements in Selenium Python
- Locating Multiple elements in Selenium Python
Python Flask Tutorial
Python Django
- How to Install Django and Set Up a Virtual Environment in 6 Steps
- Django MTV Architecture
- Django Models
- Django Views
- Django Templates
- Django Template Language
- Django Project Layout
- Django Admin Interface
- Django Database
- Django URLs and URLConf
- Django Redirects
- Django Cookies and Cookies Handling
- Django Caching
- Types of Caching in Django
- Django Sessions
- Django Forms Handling & Validation
- Django Exceptions & Error-handling
- Django Forms Validation
- Django Redirects
- Django Admin Interface
- Django Bootstrap
- Ajax in Django
- Django Migrations and Database Connectivity
- Django Web Hosting and IDE
- Django Admin Customization
- What is CRUD?
- Django ORM
- Django Request-Response Cycle
- Django ORM
- Making a basic_api with DRF
- Django Logging
- Django Applications
- Difference between Flask vs Django
- Difference between Django vs PHP
Numpy
- Numpy Introduction
- NumPy– Environment Setup
- NumPy - Data Types
- NumPy–Functions
- NumPy Histogram
- numPy.where
- numpy.sort
- NumPyfloor
- Matrix in NumPy
- NumPy Arrays
- NumPy Array Functions
- Matrix Multiplication in NumPy
- NumPy Matrix Transpose
- NumPy Array Append
- NumPy empty array
- NumPy Linear Algebra
- numpy.diff()
- numpy.unique()
- numpy.dot()
- numpy.mean()
- Numpy.argsort()
- numpy.pad()
- NumPyvstack
- NumPy sum
- NumPy Normal Distribution
- NumPylogspace()
- NumPy correlation
- Why we learn and use Numpy?
Tensorflow
- Introduction To Tensorflow
- INTRODUCTION TO DEEP LEARNING
- EXPLAIN NEURAL NETWORK?
- CONVOLUTIONAL AND RECURRENT NEURAL NETWORK
- INTRODUCTION TO TENSORFLOW
- INSTALLATION OF TENSORFLOW
- TENSORBOARD VISUALIZATION
- Linear regression in tensorflow
- Word Embedding
- Difference between CNN And RNN
- Explain Keras
- Program elements in tensorflow
- Recurrent Neural Network
- Tensorflow Object Detection
- EXPLAIN MULTILAYER PERCEPTRON
- GRADIENT DESCENT OPTIMIZATION
Interview Questions & Answers
Django Redirects
Websites, in general, have URL redirection to enhance the user experience and it’s necessary functionality to have in your websites. URL Redirection helps you gain control of your website’s flow; Django allows you to easily redirect URLs.
Need for URL Redirection
We will discuss some implementations that will justify the need for URL redirection:
- When you try to access a social media page where you want to message or like the post, then the server redirects you to the login page if you haven’t done that before.
- Not only that, some good developers have made the system that, when you sign-in/sign-up, you reach to the page you wanted to access before.
- When you are performing some important operation on the website, like changing your password. The website should redirect you to a page showing you that the operation was successful.
These were the core implementations of Url Redirections, now, let’s see what Django offers for these tasks.
Django URL Redirection
This framework has been so thoughtfully built, it really takes care of everything out of the box. Let’s see how.
When you try to access a page of Django admin without authentication, it redirects you to the log-in page.
There when you input the right credentials, it redirects you to the same page you wanted to access before the log-in page. This kind of redirection not only limits to the Django Admin but there are more operations like, when adding new objects in models via admin, changing passwords and many more.
Page Redirection is an important factor in providing a great user experience to the user. A developer will make good use of this feature of Django.
How to Page Redirect in Django?
Django has a specially made redirects function, just for this sole purpose.
As we have learned in previous tutorials, every request has a response. Requests are always Http Requests, but there can be different Responses like we returned HttpResponse in our first views.py.
We will now return, an HttpResponseRedirect instance or class object to redirect the User. You need to write redirect in place of render in the views file.
Now open views.py file. We will make a new function which will redirect the view to a different URL, which we have already added in the urls.py.
Inside the views.py, enter;
Code:
fromdjango.shortcuts import render, redirect
fromdjango.http import HttpResponse
This is the previous function:
def index(request):
returnHttpResponse(“< h1>DucatindiaDjango< /h1>Hello, you just configured your First URL”)
This is the Redirect Function:
defducat_india(request):
return redirect(‘/ducatindia’)
Now, open urls.py file
fromdjango.contrib import admin fromdjango.urls import path, include from .views import * urlpatterns = [ path('admin/', admin.site.urls), path('redirect/', ducat_india), path('ducatindia/', index), ]
We have completed the process of page-redirection, now lets run our server to see what happens.
Here we can understand the flow as when the URL associated with view function ducat_india() called the response is given as HttpResponseRedirect instance. Then the server gets the response URL as a new request and it acts accordingly.
Here you can see this in the command line, after starting the server and searching for the URL redirect/ in the urls bar.
The redirect()
This function is capable of taking more than just URLs, you can redirect your users to models, redirect to a particular URL, while also passing the key values and other needed information. But, function-based redirects are most easy to use and are quite sufficient.
We will get more power with redirects, once we learn about dynamic URLs.
The RedirectView Class-Based Redirect
When our view function is only redirecting to a certain URL, without performing any function then, Django has provided us with a special Class:
django.views.generic.base.RedirectView
You can make your redirects more dynamic and custom with this usage of Class-Based redirect. Let’s make a view for understanding this better;
Edit your urls.py file in the root folder and add this code in it:
path(‘djangotutor/’, tutorial.as_view())
Then, open the corresponding views.py file and modify this code:
fromdjango.views.generic.baseimportRedirectView
class tutorial(RedirectView): url = ‘https://data-flair.training/blogs/category/django/’
The URL is an attribute of RedirectView Class and contains the value of a URL, can take placeholders from Python, thus, your URLs can be more dynamic.
Also, instead of defining the URL in the views.py you can pass the URL in URL path itself.
fromdjango.views.generic.baseimport RedirectViewpath(‘djangotutor/’, RedirectView.as_view(url = ‘https://tutorial.ducatindia.training/blogs/category/django/’)),
We can pass the URL as an argument directly.
No, let’s learn some attributes of RedirectView:
.url –
If this attribute is used, then the value should be URL string which can have placeholders from python and they can be changed dynamically.
.pattern_name –
This is the collection of URL patterns, its like urlpatterns list for redirects.
.permanent –
This takes Boolean values of true and false. If it’s true, then the redirect becomes permanent. By default its value is false.
get_redirect_url( arguments, keyword_arguments) –
This is a method that returns a string in the form of URL. this method is responsible for generating your URL, Django allows the developer to overwrite this method any way they want.
.query_string –
This attribute takes values, true or false and by default it’s false. If this attribute is set to true then the view will add or append any query_string to the URL and return the same.
Advanced Usage of Django Redirect
redirect() can handle most of our simple redirection process which is perfect, but there are some use cases where the simple redirect() is not enough. There are some more ways for using the redirect() for advanced control over your website.
Let’s understand them according to some use cases.
-
Passing any parameter with Redirect()
When building a dynamic website, we need more than those static URLs, yes we need Dynamic URLs and also Redirections which can generate Dynamic URLs.
For example:
When defining a view function, we want that view function to redirect to another URL, which will generate dynamically and then will pass to redirect().
As we know, URLs are nothing but strings, so we can use something like this
url = ‘{}?{}’.format(base_url, Chosen_url)
Then, this URL can pass to the redirect()
redirect(url)
Here you can see that we have formatted 2 Python variables in the string. You can format as many as you want, as long as it generates a valid URL.
That’s how we can generate dynamic URLs. Currently, we don’t have enough models in our Django project to display this but yes it’s very easy to achieve this.
-
Special Redirect Codes
Django’sHttpResponse class supports status codes 301 and 302. They are the majority of use cases but if we need to return for status codes 306, 307, etc, we can generate our own HttpResponse class, just make a subclass of the HttpResponse class.
Also, you can do the same with redirect(), just by changing the response object’s value.
There are different use cases and according to that, we can use redirect() but for even more control you can use the class-based views too. They are more powerful when you want high customization with your applications but at the same time, it can also lead to errors.
Limitations of Django Redirect
Here are some of the disadvantages of Django redirects:
-
Redirects that doesn’t have any effect
django.shortcuts.redirect() is very easy to use. redirect() just returns a response object. This response object shall be returned from our views component otherwise the redirect won’t work.
For example –
When we are returning a response object from redirect which should get to the model and the response is rather going to templates directly without fetching desired data.
-
Infinite redirect Cycle
We can try this very easily. The infinite redirect cycle is when two redirects are pointing towards each other and the server just ends up redirecting over and over without stopping.
This can be disastrous for your server when working on a bigger project. The scenario where it can be harmful; when you have a redirect which is returning to some URL which then again is processed and somehow that redirection again goes to first function. This is now an infinite loop.
Just type in these two lines in your views.py.
definf1(request):
returnredirect(‘/inf2’)
definf2(request):
returnredirect(‘/inf1’)
Add these in the urlpatterns list:
path(‘inf2’, inf2),
path(‘inf1’, inf1),
The Browser shall generate this error.
Permanent & Temporary Redirects
Permanent Redirects are not so popular among developers, because of the permanent caching. Let’s understand it with a situation. Suppose you visit a website when it was in developing stage but some of its features were accessible.
And, when you tried visiting their homepage you were redirected to another page as it was in the development stage at that time.
If that redirection was permanent, then something interesting has happened. Because of the permanent redirection, your browser cached or stored that redirected page. Many would think that it’s a good thing and now the website will load faster.
But, when the website is completely developed and you want to visit their homepage by entering that URL, you will again be redirected to the page which was cached by the browser.
Notice the problem? By permanent redirection, the browser caches your page and now even if the page has been updated it will not send that URL request to the server. It will load the cached page as it is much faster without checking on the server.
Google Chrome, Mozilla and all the other browsers out there follow this pattern.
Therefore, temporary redirects are better, and you should apply permanent redirects only when you are 100% sure that the page need not be developed or want fast access to that page.