When an user open any link of Django project, before open this link, I want to apply country wise restriction. Admin has right to add country in Database table, if country is available in table, then url will open otherwise it will show a message, restricted country
3 Answers
Sure.
You'll just have to find out the user's country (e.g. the django-geoip
package and the free Maxmind database), then check the country determined with it against the list of countries in the database table/model, and raise an exception if it doesn't pass.

- 152,115
- 15
- 115
- 172
-
I have idea of above functionality in CodeIgniter. I have already applied in a PHP (CodeIgniter) project. In CodeIngiter I have created MyController and extends CI_Controller and write the function in MyController so before open any page it will restrict the user in My_Controller. Like same is there any concept availabe in Django. – tarique Jul 12 '19 at 17:53
-
Write a middleware or a view decorator to easily share the code. – AKX Jul 13 '19 at 07:54
This can be done in two ways, one mapping the IP address to a country as @AKX has already pointed to or, mapping the latitude, longitude to a country. Any front end client Web/Mobile can use their native APIs to provide lat long for a user. This data can be used to query google maps API. The api looks something like this and you'll have to register to get a key.
https://maps.googleapis.com/maps/api/geocode/json?latlng=<lat>,<long>&key=<key>
def check_for_whitelisted_country(lat, long)
r = requests.get(api)
if r.status_code == 200:
data = json.loads(r.text)
for item in data['results'][0]['address_components']:
if 'country' in item['types']:
country = item['long_name']
# if country in database return True
Now to use this, consider this example class based view.
class DoSomething(views.APIView):
def get(self, request):
try:
lat = request.GET['lat']
long = request.GET['long']
if check_whitelisted_country(lat, long):
# permit the action
else:
return Response({"Failure": "Invalid client."}, status=status.HTTP_403_FORBIDDEN)
Hope this helps.
-
I want to know, in Django where I will write code for restrict the user. For example: In my Django application more than 50 urls are there. So it is not possible to write the codition in all function. I want to create a common function and apply in a single place this function should apply for all url. – tarique Jul 12 '19 at 18:13
-
You can use Middlewares in Django ( see here ).
Write your custom middleware having request
as parameter. On each request
, we get IP address in remote_addr
. Take this IP address and find his country/region (you can use 3rd party APIs for this). see this answer
Check the user's region according to your restriction regions. If it's restricted, send error message in response.

- 331
- 1
- 5
- 14