如何检索列内容?

2024-10-05 20:08:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用queryset命令“Post.objects.values('country__name')”获取字段的内容,但出现以下错误

NoReverseMatch at /

Reverse for 'cities' with arguments '('',)' not found. 1 pattern(s) tried: ['accounts\\/cabinet\\/cities\\/(?P<pk>[0-9]+)\\/$']

虽然在django shell中键入此命令时没有收到任何错误

我的看法是:

def home(request):
        user = User.objects.all()
        cname = request.POST.get('dropdown1')
        city = Post.objects.all().distinct('city')
        country = Post.objects.values('country__name')
        print(country)
        context = {
            'country': country,
            'user': user,
            'city': city
        }

        return render(request, 'registration/home.html', context)

我的模型:

class Post(models.Model):
    title = models.CharField(max_length=255)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    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, blank=True)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.city

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

我的URL.py

urlpatterns = [
    path('accounts/register/', UserRegistrationView.as_view(), name='register'),
    path('accounts/cabinet/', views.profile, 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'),
    path('accounts/cabinet/address/<int:pk>/', views.address, name='address'),



]

Tags: pathnameviewcitymodelsasblogcountry
1条回答
网友
1楼 · 发布于 2024-10-05 20:08:01

您有一个^{} error.表示您的URL有问题

它说您正在尝试访问path('accounts/cabinet/cities/<int:pk>/', views.cities, name='cities'),,但您没有为它提供<int:pk>参数

检查您试图加载的模板,并确保它在{% url 'cities' arg1 %}块中包含该参数

相关问题 更多 >