Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

How to read shapefile in Django view helper function?

As part of my view logic I need to check if Latitude and Longitude points are withing city boundaries. To do that, I am using city shapefiles with geopandas. It all works ok locally in plain python code. However, when I run the following code in Django:

LA_geo_df = gpd.read_file('./City_Boundaries/City_Boundaries.shp')

I get the error:

DriverError at /
./City_Boundaries/City_Boundaries.shp: No such file or directory

What is the proper Django way of loading such files?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Auto-generated Django settings file will have a BASE_DIR setting that looks like this

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

This is an absolute file path to the root of your Django app. You can use this setting to build an absolute path to your file

CITY_BOUNDARIES_FILE_PATH = os.path.join(BASE_DIR, 'City_Boundaries', 'City_Boundaries.shp')

Then where you want to load the file you can use the setting

from django.conf import settings

LA_geo_df = gpd.read_file(settings.CITY_BOUNDARIES_FILE_PATH)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...