Linked Questions

Popular Questions

How can I extract City, Region, Country from a URL? Django

Asked by At

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:

new-york-ny-united-states

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)

Related Questions