本文介绍了如何从URL提取城市,地区,国家? Django的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Django应用程序目前服务于7个硬编码城市,并希望为所有世界城市提供服务,而不是像布达佩斯这样一个词,而是像纽约,纽约,美国三个层次。



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

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

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



这是我目前的城市模式:



<$城市名($ model $ M $)

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 =)#关于city的信息
image = models.ImageField(upload_to ='city_images',default = 0)#city image
slug = models.SlugField(unique = False)#city slug

#save fun
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)

提取城市,地区,国家,并将其保存在模型中,并且s to是独一无二的:

最后,这是我的全景:

  def city(request,city_name_slug):
#创建一个上下文字典,我们可以传递给
#模板呈现引擎。
context_dict = {}

#如果用户使用配置文件登录,则status = 2.
#如果用户没有配置文件登录,则status = 1
#否如果用户没有登录(status = 0)
status = navbatlogic(request = request)

#在导航栏中获取配置文件链接
#(仅在登录时才可查看+有个人资料)
slug_of_logged_user = get_profile_slug(request = request)

#我们可以找到具有给定名称的城市名称?
#如果我们不能,.get()方法会引发一个DoesNotExist异常。
#所以.get()方法返回一个模型实例或引发一个异常。
city_name = City.objects.get_or_create(
slug = city_name_slug,name = city_name_slug)

#获取注册到这个城市的用户
user_list = User.objects。过滤器(
profile__city = city_name [0])。order_by(' - profile__average_rating')[:20]

#添加登录用户的用户列表,城市名称,和
#状态变量到上下文字典
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

#如果在请求中找到p,我们正在搜索这个城市的人
如果请求中有p。 GET:
q = request.GET.get('p')
try:
#在
#username,page slug或first中查找具有搜索字词的任何用户,姓氏
user_list = User.objects.filter (
Q(username__contains = q)| Q(profile__slug__contains = q)|
Q(first_name__contains = q)| Q(last_name__contains = q)


#确保列表只包含在此城市注册的用户
user_list = user_list.filter(profile__city = city_name)

#重新添加列表到上下文字典
context_dict ['users'] = user_list
除了:
pass

#如果在请求中找到h,我们正在寻找在这个城市有一些兴趣的人

如果请求中有'h'.GET:
q = request.GET.get('h')
try :
#寻找任何类似于搜索查询的兴趣的用户
user_list = User.objects.filter(
profile__hobbies__hobby__contains = q)

#确保列表包含只有在这个城市注册的用户
user_list = user_list.filter(profile__city = city_name)

#重新添加列表到上下文字典
context_di ct ['users'] = user_list
除了:
pass

#如果在请求中找到l,我们正在搜索具有
#某些语言的人在这个城市
如果'l'在request.GET:
q = request.GET.get('l')
try:
#寻找任何用户的语言类似于搜索查询
user_list = User.objects.filter(
profile__languages__language__contains = q)

#确保列表只包含在此城市注册的用户
user_list = user_list。过滤器(profile__city = city_name)

#将列表重新添加到上下文字典
context_dict ['users'] = user_list
除了:
pass

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


解决方案

您可以使用这样的东西:

  from urllib.parse import urlparse,parse_qs 

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

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


My Django app currently serves 7 hard-coded cities and would like to make serve all world cities saved not as one word like "Budapest" but as three levels like "New York, New York, USA".

My Google-powered search field returns results like this:

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

How can I extract the values and save them in my model.

This is my current City model:

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

This line from my view only adds a new city if it doesn't exist in the database already:

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

I'd like the view to extract City, Region, Country and save them in the model and for the slug to be unique like this:

Finally, this is my View in full:

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)
解决方案

You can use urlparse for something like this:

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']

You could then split the city result to get the city, state, and country parts.

这篇关于如何从URL提取城市,地区,国家? Django的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 15:48