如何获得仅属于Django中某个国家/地区的城市名称?

时间:2019-02-15 12:01:17

标签: django

当我执行'cities = Post.objects.all()。values('city')'时,会得到所有城市的列表。但是我不知道如何按国家/地区对它们进行排序,以便在模板上显示它们。

当我打印{{city}}时,其他国家的城市名称也会出现。 我尝试使用模板{{country.city}},但一切都消失了。

我的模型。py

from PIL import Image
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    first_name = models.CharField(verbose_name="First name", max_length=255)
    last_name = models.CharField(verbose_name="First name", max_length=255)
    country = models.CharField(verbose_name="Country name", max_length=255)
    city = models.CharField(verbose_name="City name", max_length=255)
    email = models.EmailField(verbose_name="Email", max_length=255)

    def __str__(self):
        return self.username

class Post(models.Model):
    title = models.CharField(max_length=255)
    country = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    address = models.CharField(max_length=255)
    email = models.EmailField(max_length=255)
    phone = models.CharField(max_length=255)
    website = models.URLField(max_length=255)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('users:blog')

class City(models.Model):
    model = Post

    def __str__(self):
        return self.city

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = Profile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

我的views.py

def blog(request):

    context = {
            'posts': Post.objects.filter(author=request.user)
    }
    return render(request, 'users/post_list.html', context)


def countries(request):

    context = {
            'posts': Post.objects.all()
    }

    return render(request, 'users/countries.html', context)



def cities(request, pk):

    cities = Post.objects.all().values('city')

    context = {
        'cities':cities
    }

    return render(request, 'users/cities.html', context)

我的urls.py

from django.urls import path
from .views import UserRegistrationView, CabinetView, PostCreateView, PostUpdateView, PostDetailView, PostDeleteView
from . import views

app_name = 'users'

urlpatterns = [
    path('accounts/register/', UserRegistrationView.as_view(), name='register'),
    path('accounts/cabinet/', CabinetView.as_view(), name='cabinet'),
    path('accounts/cabinet/blog/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('accounts/cabinet/new/', PostCreateView.as_view(), name='post-create'),
    path('accounts/cabinet/blog/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
    path('accounts/cabinet/blog/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
    path('', views.home, name='home'),
    path('accounts/cabinet/blog/', views.blog, name='blog'),
    path('accounts/cabinet/countries/', views.countries, name='countries'),
    path('accounts/cabinet/cities/<int:pk>', views.cities, name='cities'),

]

我的国家/地区

{% extends 'shared/base.html' %}
{% load staticfiles %}

{% block content %}

<div class="content-section p-5 mt-5 pl-4">

<table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;">
       <tbody>
        <tr>
          <th>No: </th>
          <th>Countries: </th>
        </tr>
    </tbody>
</table>

{% for post in posts %}

<table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;">
       <tbody>
        <tr>
          <td>{{ post.id }}</td>
          <td><a href="{% url 'users:cities' post.pk %}">{{ post.country }}</a></td>
        </tr>
    </tbody>
</table>


{% endfor %}

{% endblock %}

</div>

我的citys.html

{% extends 'shared/base.html' %}
{% load staticfiles %}

{% block content %}

<div class="content-section p-5 mt-5 pl-4">

<table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;">
       <tbody>
        <tr>
          <th style="width: 200px;">No: </th>
          <th> Cities: </th>
        </tr>
    </tbody>
</table>

{% for city in cities %}

<table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;">

       <tbody>
        <tr>
        <td>{{ city }}</td>

        </tr>
    </tbody>


</table>


{% endfor %}
{% endblock %}

</div>

当我在country.html中单击国家名称时,我只想获取该国家/地区中城市的名称。

1 个答案:

答案 0 :(得分:0)

与其获取所有帖子,不如获取所选择的国家/地区的帖子:

caret