问题描述
我的问题是我无法建立反向匹配,很可能是我的URL定义(?)做错了。最终,我想做的是:
用户选择2个位置点,“ new_pointview”视图将这些位置点保存到数据库中。我还定义了一个包含位置信息的唯一块,并通过模型内的save()将其保存到数据库中。然后,应将用户重定向到使用我在上一步中创建的段(即/ pointview / slug)的网址(pointview视图)。这是代码:
models.py
class Points(models.Model):
starting_point_longitude = models.FloatField(null=True)
starting_point_latitude = models.FloatField(null=True)
ending_point_longitude = models.FloatField(null=True)
ending_point_latitude = models.FloatField(null=True)
url = models.SlugField(max_length=250,null=True,unique=True,blank=False)
def save(self,*args,**kwargs):
self.url = 'start_lon-{0}-start_lat-{1}-end_lon-{2}-end_lat-' \
'{3}'.format(self.starting_point_longitude,self.starting_point_latitude,self.ending_point_longitude,self.ending_point_latitude)
super(Points,self).save(*args,**kwargs)
def get_absolute_url(self):
return reverse('pointview',kwargs={'url': self.url})
views.py
def pointview(request,url):
point = get_object_or_404(Points,url=url)
content = {'starting_point_longitude':
point.starting_point_longitude,'starting_point_latitude':
point.starting_point_latitude,'ending_point_longitude':
point.ending_point_longitude,'ending_point_latitude':
point.ending_point_latitude}
return render(request,'points.html',{'user_bundle': content})
def new_pointview(request):
Points.objects.create(
starting_point_longitude=request.POST['starting_point_longitude'],starting_point_latitude=request.POST['starting_point_latitude'],ending_point_longitude=request.POST['ending_point_longitude'],ending_point_latitude=request.POST['ending_point_latitude'],)
points_filtered = Points.objects.filter(
starting_point_longitude=request.POST[
'starting_point_longitude']).filter(
starting_point_latitude=request.POST[
'starting_point_latitude'])
unique_url = points_filtered.values()[0]['url']
return redirect('/pointview/{0}/'.format(unique_url))
urls.py
urlpatterns = [
path(r'^pointview/(?P<url>[-\w]+)/$',views.pointview,name='pointview'),path('^new_pointview/',views.new_pointview,name='new_pointview'),]
错误: 当前路径pointview / start_lon-738949.9146592747-start_lat--153698.8751025315-end_lon-759997.8063993475-end_lat--168467.65638300427 /与任何URL模式都不匹配。希望您能在这里给我一些反馈。
解决方法
这是一个正则表达式问题,可以使用以下非直观的正则表达式解决:
url('^pointview/(?P<url>start_lon[--W]+start_lat[--W]+end_lon[--W]+end_lat[--W]+)/',views.pointview,name='pointview')
如果有人可以给出更优雅的解决方案,我会很有趣。