python 如何将Django中上传的GPX文件中的数据保存到PostGis数据库?

ars1skjm  于 2022-12-17  发布在  Python
关注(0)|答案(1)|浏览(123)

我有以下问题:我的目标是制作一个可以在Map上显示的gps轨迹存档。(使用Python,Django,PostgreSQL,PostGIS)我找到了一个教程:https://web.archive.org/web/20160425053015/http://ipasic.com/article/uploading-parsing-and-saving-gpx-data-postgis-geodjango文件上传工作正常,但我不知道如何将数据从文件保存到数据库,并将它们用作模型。我的代码:
forms.py

from django import forms
from .models import gpxFile

class UploadGpxForm(forms.ModelForm):

    title = forms.CharField(max_length=100)
    gpx_file = forms.FileField(required='FALSE')

    class Meta:
        model = gpxFile
        fields = ['title', 'gpx_file']

models.py

from django.contrib.gis.db import models
from django.contrib import admin
from django.contrib.gis import admin as geoadmin
from django.db.models.manager import Manager



def GPX_Folder(instance, filename):
    return "uploaded_gpx_files/%s" % (filename)

class gpxFile(models.Model):
    title = models.CharField("Title", max_length=100)
    gpx_file = models.FileField(upload_to=GPX_Folder, blank=True)

    def __unicode__(self):
        return self.title

class GPXPoint(models.Model):
    name = models.CharField("Name", max_length=50, blank=True)
    description = models.CharField("Description", max_length=250, blank=True)
    gpx_file = models.ForeignKey(gpxFile, on_delete=models.CASCADE)
    point = models.PointField()
    objects = models.Manager()

    def __unicode__(self):
        return unicode(self.name)

class GPXTrack(models.Model):
    track = models.MultiLineStringField()
    gpx_file = models.ForeignKey(gpxFile, on_delete=models.CASCADE)
    objects = models.Manager()

views.py

from django.shortcuts import render
from .forms import UploadGpxForm, Up
from .models import GPXPoint, GPXTrack, gpxFile
from django.http import HttpResponseRedirect
from django.contrib.gis.geos import Point, LineString, MultiLineString
from django.conf import settings

import gpxpy
import gpxpy.gpx

def home(request):
    #context = {
        #'notes': Note.objects.all()
    #}
    return render(request, 'gpsarchive/home.html')



def SaveGPXtoPostGIS(f, file_instance):
    
    gpx_file = open(settings.MEDIA_ROOT+ '/uploaded_gpx_files'+'/' + f.name)
    gpx = gpxpy.parse(gpx_file)

    if gpx.waypoints:        
        for waypoint in gpx.waypoints:            
            new_waypoint = GPXPoint()
            if waypoint.name:
                new_waypoint.name = waypoint.name
            else:
                new_waypoint.name = 'unknown'
            new_waypoint.point = Point(waypoint.longitude, waypoint.latitude)
            new_waypoint.gpx_file = file_instance
            new_waypoint.save()

    if gpx.tracks:
        for track in gpx.tracks:
            print("track name:" +str(track.name))
            new_track = GPXTrack()
            for segment in track.segments:
                track_list_of_points = []                
                for point in segment.points:
                    
                    point_in_segment = Point(point.longitude, point.latitude)
                    track_list_of_points.append(point_in_segment.coords)

                new_track_segment = LineString(track_list_of_points)
            
            new_track.track = MultiLineString(new_track_segment)
            new_track.gpx_file = file_instance    
            new_track.save()

def upload_gpx(request):
    if request.method == 'POST':
        file_instance = gpxFile()
        form = UploadGpxForm(request.POST, request.FILES)
        if form.is_valid():    
            form.save()
            SaveGPXtoPostGIS(request.FILES['gpx_file'], file_instance)

            return HttpResponseRedirect('success/')

    else:
        form = UploadGpxForm()

    return render(request, 'gpsarchive/form.html', {'form':form})

def upload_success(request):
    return render(request, 'gpsarchive/success.html')

正如我之前提到的,文件上传工作,不幸的是发生以下错误:**[Errno 2]没有这样的文件或目录:'/uploaded_gpx_files/3359239.gpx'**x1c 0d1x不知道导致此错误的原因,因为文件及其目录都存在,如果您有任何建议,我将非常感谢

t3psigkw

t3psigkw1#

试着像这样打开你的filefield:
gpx_文件= django_model.filefield.open(“r”)
gpx = gpxpy.解析(gpx文件)
代替
gpx_file =打开(django_模型.文件域.url,'r')
gpx = gpxpy.解析(gpx文件)
这对我起作用了。

相关问题