如何从URL中提取城市,地区,国家/地区? Django的

时间:2016-06-01 13:53:48

标签: python django django-models

我的Django应用程序目前服务于7个硬编码城市,并希望将所有世界城市的服务保存为不像“布达佩斯”这样的单词,而是像“纽约,纽约,美国”这样的三个级别。

我的Google搜索字段会返回如下结果:

http://localhost:8000/search/?city=New+York%2C+NY%2C+United+States

如何提取值并将其保存在我的模型中。

这是我目前的城市型号:

class City(models.Model):

    name = models.CharField(max_length=128, default="", unique=False)  # city name
    country = models.CharField(max_length=128, default="Scotland")  # country name
    information = models.CharField(max_length=3000, default="")  # information about city
    image = models.ImageField(upload_to='city_images', default=0)#city image
    slug = models.SlugField(unique=False)  # city slug

    # save function
    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(City, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name

如果数据库中不存在新行,我的视图中的这一行只会添加一个新城市:

city_name = City.objects.get_or_create(slug=city_name_slug, name=city_name_slug)

我想要提取城市,地区,国家的视图,并将它们保存在模型中,并使slug像这样独特:

  

新纽约NY-联合态

最后,这是我的观点:

def city(request, city_name_slug):
    # Create a context dictionary which we can pass to the 
    # template rendering engine.
    context_dict = {}

    # if the user is logged in with a profile then status = 2. 
    # else if the user is logged in without a profile then status = 1
    # else if the user is not logged in (status = 0)
    status = navbatlogic(request=request)

    # to get the profile link in the nav bar 
    # (only viewable when logged + has a profile)
    slug_of_logged_user = get_profile_slug(request=request)

    # Can we find a city name slug with the given name?
    # If we can't, the .get() method raises a DoesNotExist exception.
    # So the .get() method returns one model instance or raises an exception.
    city_name = City.objects.get_or_create(
        slug=city_name_slug, name=city_name_slug)

    # Get the users registered to this city
    user_list = User.objects.filter(
        profile__city=city_name[0]).order_by('-profile__average_rating')[:20]

    # Add the user list, city name, slug of the logged-in user, and a 
    # status variable to the context dictionary
    context_dict['users'] = user_list
    context_dict['city'] = city_name[0]
    context_dict['slug_of_logged_user'] = slug_of_logged_user
    context_dict['status'] = status

    # If p is found in the request, we are searching for people in this city
    if 'p' in request.GET:
        q = request.GET.get('p')
        try:  
            # Look for any user with the search term in their 
            # username, page slug or first and last names
            user_list = User.objects.filter(
                Q(username__contains=q) | Q(profile__slug__contains=q) | 
                Q(first_name__contains=q) | Q(last_name__contains=q)
            )

            # Make sure list contains only users registered in this city
            user_list = user_list.filter(profile__city=city_name)

            # Re-add list to context dictionary
            context_dict['users'] = user_list
        except:
            pass

    # If h is found in the request, we are searching for people 
    # with a certain hobby in this city
    if 'h' in request.GET:
        q = request.GET.get('h')
        try:
            # Look for any user with hobbies similar to the search query
            user_list = User.objects.filter(
                profile__hobbies__hobby__contains=q)

            # Make sure list contains only users registered in this city
            user_list = user_list.filter(profile__city=city_name)

            # Re-add list to context dictionary
            context_dict['users'] = user_list
        except:
            pass

    # If l is found in the request, we are searching for people with 
    # a certain language in this city
    if 'l' in request.GET:
        q = request.GET.get('l')
        try:
            # Look for any user with languages similar to the search query
            user_list = User.objects.filter(
                profile__languages__language__contains=q)

            # Make sure list contains only users registered in this city
            user_list = user_list.filter(profile__city=city_name)

            # Re-add list to context dictionary
            context_dict['users'] = user_list
        except:
            pass

    return render(request, 'cityProfile.html', context_dict)

3 个答案:

答案 0 :(得分:2)

您可以将urlparse用于以下内容:

from urllib.parse import urlparse, parse_qs

u = urlparse('http://localhost:8000/search/?city=New+York%2C+NY%2C+United+States')
q = parse_qs(u.query)
city = q['city']

然后,您可以split城市结果来获取城市,州和国家/地区部分。

答案 1 :(得分:0)

最好从结构良好的数据源(例如Google地理编码服务)中提取这些组件,这样您就可以可靠地分辨数据的哪一部分映射到行政区划。 如果您从https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple获取示例,那么您将在address_components中获得具有3层结构的JSON对象:

"address_components" : [
        {
           "long_name" : "New York",
           "short_name" : "New York",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "New York",
           "short_name" : "NY",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        }
     ]

然而再次,小心,并非所有地方都有3层...尝试一些极端的情况,看看你得到了什么(例如梵蒂冈城,南极洲等)

答案 2 :(得分:0)

如果您提供更多的URL作为示例,那就太好了。但是,从您提供的URL中,我只需写几行即可获得所需的城市和国家/地区名称:

city: New York
title: NY
country: United States

代码如下:

url = 'http://localhost:8000/search/?city=New+York%2C+NY%2C+United+States'
city = url.split('/?city=')[1].split('%2C')
name, title, country = [c.replace('+',' ').strip() for c in city]

希望您会发现它有用。谢谢。