refactoring

This commit is contained in:
Anatoly 2019-12-09 13:34:17 +03:00
parent 943dce90c7
commit d330aa5205
15 changed files with 28 additions and 216 deletions

View File

@ -79,6 +79,7 @@ class Collection(ProjectBaseMixin, CollectionDateMixin,
slug = models.SlugField(max_length=50, unique=True, slug = models.SlugField(max_length=50, unique=True,
verbose_name=_('Collection slug'), editable=True, null=True) verbose_name=_('Collection slug'), editable=True, null=True)
old_id = models.IntegerField(null=True, blank=True) old_id = models.IntegerField(null=True, blank=True)
objects = CollectionQuerySet.as_manager() objects = CollectionQuerySet.as_manager()
class Meta: class Meta:

View File

@ -11,6 +11,7 @@ import phonenumber_field.modelfields
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('location', '0027_auto_20191118_1313'),
('establishment', '0062_auto_20191117_1117'), ('establishment', '0062_auto_20191117_1117'),
] ]

View File

@ -21,8 +21,8 @@ class Image(ProjectBaseMixin, SORLImageMixin, PlatformMixin):
(VERTICAL, _('Vertical')), (VERTICAL, _('Vertical')),
) )
image = SORLImageField(upload_to=image_path, image = SORLImageField(max_length=255, upload_to=image_path,
verbose_name=_('image file'), max_length=255) verbose_name=_('image file'))
orientation = models.PositiveSmallIntegerField(choices=ORIENTATIONS, orientation = models.PositiveSmallIntegerField(choices=ORIENTATIONS,
blank=True, null=True, default=None, blank=True, null=True, default=None,
verbose_name=_('image orientation')) verbose_name=_('image orientation'))

View File

@ -6,6 +6,7 @@ from django.db import migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('location', '0027_auto_20191118_1313'),
('location', '0027_auto_20191118_1011'), ('location', '0027_auto_20191118_1011'),
] ]

View File

@ -6,6 +6,7 @@ from django.db import migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('location', '0027_auto_20191118_1313'),
('location', '0027_auto_20191118_1011'), ('location', '0027_auto_20191118_1011'),
] ]

View File

@ -106,10 +106,12 @@ class City(GalleryModelMixin):
"""Region model.""" """Region model."""
name = models.CharField(_('name'), max_length=250) name = models.CharField(_('name'), max_length=250)
name_translated = TJSONField(blank=True, null=True, default=None, 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) code = models.CharField(_('code'), max_length=250)
region = models.ForeignKey( region = models.ForeignKey(Region, on_delete=models.CASCADE,
Region, verbose_name=_('parent region'), on_delete=models.CASCADE, blank=True, null=True) blank=True, null=True,
verbose_name=_('parent region'))
country = models.ForeignKey( country = models.ForeignKey(
Country, verbose_name=_('country'), on_delete=models.CASCADE) Country, verbose_name=_('country'), on_delete=models.CASCADE)

View File

@ -4,7 +4,6 @@ from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers from rest_framework import serializers
from location import models from location import models
from utils.serializers import TranslatedField from utils.serializers import TranslatedField
from gallery.models import Image
class CountrySerializer(serializers.ModelSerializer): 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): class CitySerializer(serializers.ModelSerializer):
"""City serializer.""" """City serializer."""
region = RegionSerializer(read_only=True) region = RegionSerializer(read_only=True)
@ -178,7 +82,6 @@ class CitySerializer(serializers.ModelSerializer):
queryset=models.Country.objects.all(), queryset=models.Country.objects.all(),
write_only=True write_only=True
) )
city_gallery = CityGallerySerializer(many=True, read_only=True)
country = CountrySerializer(read_only=True) country = CountrySerializer(read_only=True)
class Meta: class Meta:
@ -190,10 +93,9 @@ class CitySerializer(serializers.ModelSerializer):
'region', 'region',
'region_id', 'region_id',
'country_id', 'country_id',
'country',
'postal_code', 'postal_code',
'is_island', 'is_island',
'city_gallery',
'country'
] ]

View File

@ -162,7 +162,6 @@ class CityTests(BaseTestCase):
response = self.client.post('/api/back/location/cities/', data=data, format='json') response = self.client.post('/api/back/location/cities/', data=data, format='json')
response_data = response.json() response_data = response.json()
print(response_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = self.client.get(f'/api/back/location/cities/{response_data["id"]}/', format='json') response = self.client.get(f'/api/back/location/cities/{response_data["id"]}/', format='json')

View File

@ -1,7 +1,6 @@
from transfer.serializers import location as location_serializers from transfer.serializers import location as location_serializers
from transfer import models as transfer_models from transfer import models as transfer_models
from location.models import Country, Region, City, Address, WineRegion, CityGallery from location.models import Country, Region, City, Address, CityGallery
from pprint import pprint
import json import json
from django.db.transaction import atomic from django.db.transaction import atomic
@ -9,7 +8,6 @@ from gallery.models import Image
from pprint import pprint from pprint import pprint
from django.conf import settings from django.conf import settings
from django.core.exceptions import MultipleObjectsReturned
from collection.models import Collection from collection.models import Collection
from requests import get from requests import get
from main.models import AwardType from main.models import AwardType
@ -692,9 +690,6 @@ def add_fake_country():
region.save() region.save()
data_types = { data_types = {
"dictionaries": [ "dictionaries": [
transfer_countries, transfer_countries,
@ -717,9 +712,14 @@ data_types = {
"fix_location": [ "fix_location": [
fix_location_models fix_location_models
], ],
"remove_old_locations":[remove_old_records], "remove_old_locations": [
remove_old_records
],
"fill_city_gallery": [transfer_city_gallery], "fill_city_gallery": [
"add_fake_country": [add_fake_country] transfer_city_gallery
],
"add_fake_country": [
add_fake_country
],
} }

View File

@ -9,13 +9,8 @@ urlpatterns = [
path('addresses/', views.AddressListView.as_view(), name='address-list'), path('addresses/', views.AddressListView.as_view(), name='address-list'),
path('addresses/<int:pk>/', views.AddressRetrieveView.as_view(), name='address-retrieve'), path('addresses/<int:pk>/', views.AddressRetrieveView.as_view(), name='address-retrieve'),
path('cities/', views.CityListCreateView.as_view(), name='city-list'), path('cities/', views.CityListView.as_view(), name='city-list'),
path('cities/<int:pk>/', views.CityRUDView.as_view(), name='city-detail'), path('cities/<int:pk>/', views.CityRetrieveView.as_view(), name='city-retrieve'),
path('cities/<int:pk>/gallery/', views.CityGalleryListView.as_view(),
name='gallery-list'),
path('cities/<int:pk>/gallery/<int:image_id>/', views.CityGalleryCreateDestroyView.as_view(),
name='gallery-create-destroy'),
path('countries/', views.CountryListView.as_view(), name='country-list'), path('countries/', views.CountryListView.as_view(), name='country-list'),
path('countries/<int:pk>/', views.CountryRetrieveView.as_view(), name='country-retrieve'), path('countries/<int:pk>/', views.CountryRetrieveView.as_view(), name='country-retrieve'),

View File

@ -1,10 +1,4 @@
"""Location app views.""" """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 generics
from rest_framework import permissions from rest_framework import permissions
from django.db.models.expressions import RawSQL from django.db.models.expressions import RawSQL
@ -89,9 +83,9 @@ class RegionUpdateView(RegionViewMixin, generics.UpdateAPIView):
# City # City
class CityRUDView(generics.RetrieveUpdateDestroyAPIView): class CityCreateView(CityViewMixin, generics.CreateAPIView):
"""Create view for model City"""
serializer_class = serializers.CitySerializer serializer_class = serializers.CitySerializer
permission_classes = (permissions.AllowAny,) # TODO: remove after tests
class CityRetrieveView(CityViewMixin, generics.RetrieveAPIView): class CityRetrieveView(CityViewMixin, generics.RetrieveAPIView):
@ -121,70 +115,6 @@ class CityUpdateView(CityViewMixin, generics.UpdateAPIView):
serializer_class = serializers.CitySerializer 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 # Address
class AddressCreateView(AddressViewMixin, generics.CreateAPIView): class AddressCreateView(AddressViewMixin, generics.CreateAPIView):
"""Create view for model Address""" """Create view for model Address"""

View File

@ -2,11 +2,9 @@
from django.db.models.signals import post_save from django.db.models.signals import post_save
from django.dispatch import receiver from django.dispatch import receiver
from django_elasticsearch_dsl.registries import registry from django_elasticsearch_dsl.registries import registry
from utils.signals import skip_signal
@receiver(post_save) @receiver(post_save)
@skip_signal()
def update_document(sender, **kwargs): def update_document(sender, **kwargs):
from establishment.models import Establishment from establishment.models import Establishment
app_label = sender._meta.app_label app_label = sender._meta.app_label

View File

@ -16,7 +16,7 @@ class Command(BaseCommand):
'recipe', 'recipe',
'partner', 'partner',
'establishment', # №3 - перенос заведений 'establishment', # №3 - перенос заведений
'gallery', #!!!! 'gallery',
'commercial', # перенос рекламмы (очередность не важна) 'commercial', # перенос рекламмы (очередность не важна)
'overlook', # №5 - перенос языков, отзывов 'overlook', # №5 - перенос языков, отзывов
'tmp', 'tmp',
@ -28,7 +28,7 @@ class Command(BaseCommand):
LONG_DATA_TYPES = [ LONG_DATA_TYPES = [
'update_country_flag', 'update_country_flag',
'comment', #!!!! 'comment',
'inquiries', # №6 - перенос запросов оценок 'inquiries', # №6 - перенос запросов оценок
'wine_characteristics', # №5 - перенос характиристик вин 'wine_characteristics', # №5 - перенос характиристик вин
'product', # №5 - перенос продуктов 'product', # №5 - перенос продуктов

View File

@ -6,7 +6,6 @@ from location import models
from transfer.mixins import TransferSerializerMixin from transfer.mixins import TransferSerializerMixin
from utils.methods import get_point_from_coordinates from utils.methods import get_point_from_coordinates
from transfer.models import Cepages from transfer.models import Cepages
from tag.models import TagCategory
from django.utils.text import slugify from django.utils.text import slugify
from django.contrib.gis.geos import Point from django.contrib.gis.geos import Point
@ -351,12 +350,6 @@ class WineVillage(TransferSerializerMixin):
attrs['wine_region'] = self.get_wine_region(parent_id) attrs['wine_region'] = self.get_wine_region(parent_id)
return attrs 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): class CityMapSerializer(serializers.ModelSerializer):
id = serializers.IntegerField() id = serializers.IntegerField()

View File

@ -75,7 +75,6 @@ PROJECT_APPS = [
'favorites.apps.FavoritesConfig', 'favorites.apps.FavoritesConfig',
'rating.apps.RatingConfig', 'rating.apps.RatingConfig',
'tag.apps.TagConfig', 'tag.apps.TagConfig',
# 'transfer.apps.TransferConfig',
] ]
EXTERNAL_APPS = [ EXTERNAL_APPS = [
@ -157,9 +156,6 @@ DATABASES = {
'PASSWORD': os.environ.get('DB_PASSWORD'), 'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOSTNAME'), 'HOST': os.environ.get('DB_HOSTNAME'),
'PORT': os.environ.get('DB_PORT'), '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_web': {'size': (940, 430), }, # при загрузке через контент эдитор
'news_editor_mobile': {'size': (343, 260), }, # через контент эдитор в мобильном браузерe 'news_editor_mobile': {'size': (343, 260), }, # через контент эдитор в мобильном браузерe
'avatar_comments_web': {'size': (116, 116), }, '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), },
} }
} }