From d330aa5205a9541131a0fd1b1a3fc8f7e3957066 Mon Sep 17 00:00:00 2001 From: Anatoly Date: Mon, 9 Dec 2019 13:34:17 +0300 Subject: [PATCH] refactoring --- apps/collection/models.py | 1 + apps/establishment/migrations/0063_company.py | 1 + apps/gallery/models.py | 4 +- .../migrations/0028_merge_20191118_1507.py | 1 + .../migrations/0028_merge_20191119_0647.py | 1 + apps/location/models.py | 8 +- apps/location/serializers/common.py | 100 +----------------- apps/location/tests.py | 1 - apps/location/transfer_data.py | 20 ++-- apps/location/urls/common.py | 9 +- apps/location/views/common.py | 74 +------------ apps/search_indexes/signals.py | 2 - apps/transfer/management/commands/transfer.py | 4 +- apps/transfer/serializers/location.py | 7 -- project/settings/base.py | 11 -- 15 files changed, 28 insertions(+), 216 deletions(-) diff --git a/apps/collection/models.py b/apps/collection/models.py index c5a9aac8..7acd9991 100644 --- a/apps/collection/models.py +++ b/apps/collection/models.py @@ -79,6 +79,7 @@ class Collection(ProjectBaseMixin, CollectionDateMixin, slug = models.SlugField(max_length=50, unique=True, verbose_name=_('Collection slug'), editable=True, null=True) old_id = models.IntegerField(null=True, blank=True) + objects = CollectionQuerySet.as_manager() class Meta: diff --git a/apps/establishment/migrations/0063_company.py b/apps/establishment/migrations/0063_company.py index f72c4fd9..1f9b4aa3 100644 --- a/apps/establishment/migrations/0063_company.py +++ b/apps/establishment/migrations/0063_company.py @@ -11,6 +11,7 @@ import phonenumber_field.modelfields class Migration(migrations.Migration): dependencies = [ + ('location', '0027_auto_20191118_1313'), ('establishment', '0062_auto_20191117_1117'), ] diff --git a/apps/gallery/models.py b/apps/gallery/models.py index ba0c28b3..92cc4674 100644 --- a/apps/gallery/models.py +++ b/apps/gallery/models.py @@ -21,8 +21,8 @@ class Image(ProjectBaseMixin, SORLImageMixin, PlatformMixin): (VERTICAL, _('Vertical')), ) - image = SORLImageField(upload_to=image_path, - verbose_name=_('image file'), max_length=255) + image = SORLImageField(max_length=255, upload_to=image_path, + verbose_name=_('image file')) orientation = models.PositiveSmallIntegerField(choices=ORIENTATIONS, blank=True, null=True, default=None, verbose_name=_('image orientation')) diff --git a/apps/location/migrations/0028_merge_20191118_1507.py b/apps/location/migrations/0028_merge_20191118_1507.py index 8113e03c..f7b41a63 100644 --- a/apps/location/migrations/0028_merge_20191118_1507.py +++ b/apps/location/migrations/0028_merge_20191118_1507.py @@ -6,6 +6,7 @@ from django.db import migrations class Migration(migrations.Migration): dependencies = [ + ('location', '0027_auto_20191118_1313'), ('location', '0027_auto_20191118_1011'), ] diff --git a/apps/location/migrations/0028_merge_20191119_0647.py b/apps/location/migrations/0028_merge_20191119_0647.py index cd555fd6..40d79f13 100644 --- a/apps/location/migrations/0028_merge_20191119_0647.py +++ b/apps/location/migrations/0028_merge_20191119_0647.py @@ -6,6 +6,7 @@ from django.db import migrations class Migration(migrations.Migration): dependencies = [ + ('location', '0027_auto_20191118_1313'), ('location', '0027_auto_20191118_1011'), ] diff --git a/apps/location/models.py b/apps/location/models.py index 23311658..ac9acd45 100644 --- a/apps/location/models.py +++ b/apps/location/models.py @@ -106,10 +106,12 @@ class City(GalleryModelMixin): """Region model.""" name = models.CharField(_('name'), max_length=250) name_translated = TJSONField(blank=True, null=True, default=None, - verbose_name=_('Translated name'), help_text='{"en-GB":"some text"}') + verbose_name=_('Translated name'), + help_text='{"en-GB":"some text"}') code = models.CharField(_('code'), max_length=250) - region = models.ForeignKey( - Region, verbose_name=_('parent region'), on_delete=models.CASCADE, blank=True, null=True) + region = models.ForeignKey(Region, on_delete=models.CASCADE, + blank=True, null=True, + verbose_name=_('parent region')) country = models.ForeignKey( Country, verbose_name=_('country'), on_delete=models.CASCADE) diff --git a/apps/location/serializers/common.py b/apps/location/serializers/common.py index 05e6b4cb..6255e67f 100644 --- a/apps/location/serializers/common.py +++ b/apps/location/serializers/common.py @@ -4,7 +4,6 @@ from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from location import models from utils.serializers import TranslatedField -from gallery.models import Image class CountrySerializer(serializers.ModelSerializer): @@ -70,101 +69,6 @@ class CityShortSerializer(serializers.ModelSerializer): ) -class CropImageSerializer(serializers.Serializer): - """Serializer for crop images for City object.""" - - xsmall_url = serializers.SerializerMethodField() - small_url = serializers.SerializerMethodField() - medium_url = serializers.SerializerMethodField() - large_url = serializers.SerializerMethodField() - xlarge_url = serializers.SerializerMethodField() - detail_url = serializers.SerializerMethodField() - - def get_xsmall_url(self, obj): - """Get crop preview.""" - return obj.instance.get_image_url('location_city_xsmall') - - def get_small_url(self, obj): - """Get crop preview.""" - return obj.instance.get_image_url('location_city_small') - - def get_medium_url(self, obj): - """Get crop preview.""" - return obj.instance.get_image_url('location_city_medium') - - def get_large_url(self, obj): - """Get crop preview.""" - return obj.instance.get_image_url('location_city_large') - - def get_xlarge_url(self, obj): - """Get crop preview.""" - return obj.instance.get_image_url('location_city_xlarge') - - def get_detail_url(self, obj): - """Get crop preview.""" - return obj.instance.get_image_url('location_city_detail') - - -class CityImageSerializer(serializers.ModelSerializer): - """Serializer for returning crop images of news image.""" - - orientation_display = serializers.CharField(source='get_orientation_display', - read_only=True) - original_url = serializers.URLField(source='image.url') - auto_crop_images = CropImageSerializer(source='image', allow_null=True) - - class Meta: - model = Image - fields = [ - 'id', - 'title', - 'orientation_display', - 'original_url', - 'auto_crop_images', - ] - extra_kwargs = { - 'orientation': {'write_only': True} - } - - -class CityGallerySerializer(serializers.ModelSerializer): - """Serializer class for model NewsGallery.""" - - class Meta: - """Meta class""" - - model = models.CityGallery - fields = [ - 'id', - 'is_main', - ] - - def get_request_kwargs(self): - """Get url kwargs from request.""" - return self.context.get('request').parser_context.get('kwargs') - - def validate(self, attrs): - """Override validate method.""" - news_pk = self.get_request_kwargs().get('pk') - image_id = self.get_request_kwargs().get('image_id') - - news_qs = models.City.objects.filter(pk=news_pk) - image_qs = Image.objects.filter(id=image_id) - - if not news_qs.exists(): - raise serializers.ValidationError({'detail': _('News not found')}) - if not image_qs.exists(): - raise serializers.ValidationError({'detail': _('Image not found')}) - - news = news_qs.first() - image = image_qs.first() - - attrs['news'] = news - attrs['image'] = image - - return attrs - - class CitySerializer(serializers.ModelSerializer): """City serializer.""" region = RegionSerializer(read_only=True) @@ -178,7 +82,6 @@ class CitySerializer(serializers.ModelSerializer): queryset=models.Country.objects.all(), write_only=True ) - city_gallery = CityGallerySerializer(many=True, read_only=True) country = CountrySerializer(read_only=True) class Meta: @@ -190,10 +93,9 @@ class CitySerializer(serializers.ModelSerializer): 'region', 'region_id', 'country_id', + 'country', 'postal_code', 'is_island', - 'city_gallery', - 'country' ] diff --git a/apps/location/tests.py b/apps/location/tests.py index b48d7206..960f7f2b 100644 --- a/apps/location/tests.py +++ b/apps/location/tests.py @@ -162,7 +162,6 @@ class CityTests(BaseTestCase): response = self.client.post('/api/back/location/cities/', data=data, format='json') response_data = response.json() - print(response_data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) response = self.client.get(f'/api/back/location/cities/{response_data["id"]}/', format='json') diff --git a/apps/location/transfer_data.py b/apps/location/transfer_data.py index b28f3480..1959e41f 100644 --- a/apps/location/transfer_data.py +++ b/apps/location/transfer_data.py @@ -1,7 +1,6 @@ from transfer.serializers import location as location_serializers from transfer import models as transfer_models -from location.models import Country, Region, City, Address, WineRegion, CityGallery -from pprint import pprint +from location.models import Country, Region, City, Address, CityGallery import json from django.db.transaction import atomic @@ -9,7 +8,6 @@ from gallery.models import Image from pprint import pprint from django.conf import settings -from django.core.exceptions import MultipleObjectsReturned from collection.models import Collection from requests import get from main.models import AwardType @@ -692,9 +690,6 @@ def add_fake_country(): region.save() - - - data_types = { "dictionaries": [ transfer_countries, @@ -717,9 +712,14 @@ data_types = { "fix_location": [ fix_location_models ], - "remove_old_locations":[remove_old_records], + "remove_old_locations": [ + remove_old_records + ], - "fill_city_gallery": [transfer_city_gallery], - "add_fake_country": [add_fake_country] - + "fill_city_gallery": [ + transfer_city_gallery + ], + "add_fake_country": [ + add_fake_country + ], } diff --git a/apps/location/urls/common.py b/apps/location/urls/common.py index 3f86dd29..c3ea21db 100644 --- a/apps/location/urls/common.py +++ b/apps/location/urls/common.py @@ -9,13 +9,8 @@ urlpatterns = [ path('addresses/', views.AddressListView.as_view(), name='address-list'), path('addresses//', views.AddressRetrieveView.as_view(), name='address-retrieve'), - path('cities/', views.CityListCreateView.as_view(), name='city-list'), - path('cities//', views.CityRUDView.as_view(), name='city-detail'), - - path('cities//gallery/', views.CityGalleryListView.as_view(), - name='gallery-list'), - path('cities//gallery//', views.CityGalleryCreateDestroyView.as_view(), - name='gallery-create-destroy'), + path('cities/', views.CityListView.as_view(), name='city-list'), + path('cities//', views.CityRetrieveView.as_view(), name='city-retrieve'), path('countries/', views.CountryListView.as_view(), name='country-list'), path('countries//', views.CountryRetrieveView.as_view(), name='country-retrieve'), diff --git a/apps/location/views/common.py b/apps/location/views/common.py index 11ed51da..660a1dbe 100644 --- a/apps/location/views/common.py +++ b/apps/location/views/common.py @@ -1,10 +1,4 @@ """Location app views.""" -from django.conf import settings -from django.db.transaction import on_commit -from django.shortcuts import get_object_or_404 -from rest_framework import generics, permissions, status -from rest_framework.response import Response -from gallery.tasks import delete_image from rest_framework import generics from rest_framework import permissions from django.db.models.expressions import RawSQL @@ -89,9 +83,9 @@ class RegionUpdateView(RegionViewMixin, generics.UpdateAPIView): # City -class CityRUDView(generics.RetrieveUpdateDestroyAPIView): +class CityCreateView(CityViewMixin, generics.CreateAPIView): + """Create view for model City""" serializer_class = serializers.CitySerializer - permission_classes = (permissions.AllowAny,) # TODO: remove after tests class CityRetrieveView(CityViewMixin, generics.RetrieveAPIView): @@ -121,70 +115,6 @@ class CityUpdateView(CityViewMixin, generics.UpdateAPIView): serializer_class = serializers.CitySerializer -class CityGalleryListView(generics.ListAPIView): - """Resource for returning gallery for news for back-office users.""" - serializer_class = serializers.CityImageSerializer - - permission_classes = (permissions.IsAuthenticated,) - queryset = models.City.objects - - def get_object(self): - """Override get_object method.""" - qs = super(CityGalleryListView, self).get_queryset() - city = get_object_or_404(qs, pk=self.kwargs['pk']) - - # May raise a permission denied - self.check_object_permissions(self.request, city) - - return city - - def get_queryset(self): - """Override get_queryset method.""" - return self.get_object().gallery.all() - - -class CityGalleryCreateDestroyView(generics.CreateAPIView, - generics.DestroyAPIView): - - permission_classes = (permissions.IsAuthenticated,) - queryset = models.City.objects - - """Resource for a create gallery for news for back-office users.""" - serializer_class = serializers.CityGallerySerializer - - def get_object(self): - """ - Returns the object the view is displaying. - """ - city_qs = self.filter_queryset(self.get_queryset()) - - city = get_object_or_404(city_qs, pk=self.kwargs['pk']) - gallery = get_object_or_404(city.news_gallery, image_id=self.kwargs['image_id']) - - # May raise a permission denied - self.check_object_permissions(self.request, gallery) - - return gallery - - def create(self, request, *args, **kwargs): - """Overridden create method""" - super().create(request, *args, **kwargs) - return Response(status=status.HTTP_201_CREATED) - - def destroy(self, request, *args, **kwargs): - """Override destroy method.""" - gallery_obj = self.get_object() - if settings.USE_CELERY: - on_commit(lambda: delete_image.delay(image_id=gallery_obj.image.id, - completely=False)) - else: - on_commit(lambda: delete_image(image_id=gallery_obj.image.id, - completely=False)) - # Delete an instances of NewsGallery model - gallery_obj.delete() - return Response(status=status.HTTP_204_NO_CONTENT) - - # Address class AddressCreateView(AddressViewMixin, generics.CreateAPIView): """Create view for model Address""" diff --git a/apps/search_indexes/signals.py b/apps/search_indexes/signals.py index dfd795dd..5bee4e17 100644 --- a/apps/search_indexes/signals.py +++ b/apps/search_indexes/signals.py @@ -2,11 +2,9 @@ from django.db.models.signals import post_save from django.dispatch import receiver from django_elasticsearch_dsl.registries import registry -from utils.signals import skip_signal @receiver(post_save) -@skip_signal() def update_document(sender, **kwargs): from establishment.models import Establishment app_label = sender._meta.app_label diff --git a/apps/transfer/management/commands/transfer.py b/apps/transfer/management/commands/transfer.py index 76e7c923..d10807b1 100644 --- a/apps/transfer/management/commands/transfer.py +++ b/apps/transfer/management/commands/transfer.py @@ -16,7 +16,7 @@ class Command(BaseCommand): 'recipe', 'partner', 'establishment', # №3 - перенос заведений - 'gallery', #!!!! + 'gallery', 'commercial', # перенос рекламмы (очередность не важна) 'overlook', # №5 - перенос языков, отзывов 'tmp', @@ -28,7 +28,7 @@ class Command(BaseCommand): LONG_DATA_TYPES = [ 'update_country_flag', - 'comment', #!!!! + 'comment', 'inquiries', # №6 - перенос запросов оценок 'wine_characteristics', # №5 - перенос характиристик вин 'product', # №5 - перенос продуктов diff --git a/apps/transfer/serializers/location.py b/apps/transfer/serializers/location.py index f1a1cea3..e7435054 100644 --- a/apps/transfer/serializers/location.py +++ b/apps/transfer/serializers/location.py @@ -6,7 +6,6 @@ from location import models from transfer.mixins import TransferSerializerMixin from utils.methods import get_point_from_coordinates from transfer.models import Cepages -from tag.models import TagCategory from django.utils.text import slugify from django.contrib.gis.geos import Point @@ -351,12 +350,6 @@ class WineVillage(TransferSerializerMixin): attrs['wine_region'] = self.get_wine_region(parent_id) return attrs - def get_wine_region(self, parent_id): - qs = models.WineRegion.objects.filter(old_id=parent_id) - if qs.exists(): - return qs.first() - - class CityMapSerializer(serializers.ModelSerializer): id = serializers.IntegerField() diff --git a/project/settings/base.py b/project/settings/base.py index 5b5faea3..5a48c261 100644 --- a/project/settings/base.py +++ b/project/settings/base.py @@ -75,7 +75,6 @@ PROJECT_APPS = [ 'favorites.apps.FavoritesConfig', 'rating.apps.RatingConfig', 'tag.apps.TagConfig', - # 'transfer.apps.TransferConfig', ] EXTERNAL_APPS = [ @@ -157,9 +156,6 @@ DATABASES = { 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOSTNAME'), 'PORT': os.environ.get('DB_PORT'), - 'OPTIONS': { - 'options': '-c search_path=gm' - }, }, } @@ -374,13 +370,6 @@ THUMBNAIL_ALIASES = { 'news_editor_web': {'size': (940, 430), }, # при загрузке через контент эдитор 'news_editor_mobile': {'size': (343, 260), }, # через контент эдитор в мобильном браузерe 'avatar_comments_web': {'size': (116, 116), }, - # location.city - 'location_city_xsmall': {'size': (70, 70), }, - 'location_city_small': {'size': (140, 140), }, - 'location_city_medium': {'size': (280, 280), }, - 'location_city_large': {'size': (280, 280), }, - 'location_city_xlarge': {'size': (560, 560), }, - 'location_city_detail': {'size': (1120, 1120), }, } }