每次用户添加帖子时,他的信息都会重复。我该如何预防?

时间:2019-02-15 13:35:30

标签: python django

每次用户添加新帖子时,都会重复显示用户信息中的国家/地区名称。

例如。来自美国的某人添加了帖子,并多次给美国命名。

我尝试使用不同的'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'),

]

我的国家/地区

{% 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>

2 个答案:

答案 0 :(得分:0)

我猜您正在使用SQLite数据库。 .distinct()不能与sqlite3一起使用,因此您将不得不切换到诸如postgresql之类的东西来使用它或修改您的查询。

因此,如果您无法更改数据库,则只需手动过滤数据库即可。但认为切换到另一个数据库将是解决此问题的最佳解决方案

答案 1 :(得分:0)

如果仅需要国家列表,为什么不使用.values()?我认为,如果您只想 国家/地区列表,则下面的代码应该可以完成这项工作?

countries = Post.objects.values("country").distinct()

结果将是带有dict类对象的查询集,即:

[{"country": "USA"}, {"country": "Canada"}, ...]