每次用户添加新帖子时,都会重复显示用户信息中的国家/地区名称。
例如。来自美国的某人添加了帖子,并多次给美国命名。
我尝试使用不同的'country = Post.objects.all()。distinct('country')',然后出现此错误 “此数据库后端不支持DISTINCT ON字段”。
我的views.py
def countries(request):
country = Post.objects.all().distinct('country')
context = {
'posts': country
}
return render(request, 'users/countries.html', context)
我的models.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 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)
我的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'),
]
我的国家/地区