change display_country_code type of returning value, refactored create guide method, added filtering award type list, change name of username_random -> string_random

This commit is contained in:
Anatoly 2020-02-03 17:16:29 +03:00
parent 4d52ec57c4
commit 400b5ac402
10 changed files with 50 additions and 24 deletions

View File

@ -1,10 +1,8 @@
"""Common serializer for application authorization"""
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import password_validation as password_validators
from django.db.models import Q
from rest_framework import serializers
from rest_framework.generics import get_object_or_404
from account import models as account_models
from authorization import tasks
@ -69,9 +67,9 @@ class SignupSerializer(serializers.ModelSerializer):
username = validated_data.get('username')
if not username:
username = utils_methods.username_random()
username = utils_methods.string_random()
while account_models.User.objects.filter(username__iexact=username).exists():
username = utils_methods.username_random()
username = utils_methods.string_random()
obj = account_models.User.objects.make(
username=validated_data.get('username'),

View File

@ -337,15 +337,6 @@ class Guide(ProjectBaseMixin, CollectionNameMixin, CollectionDateMixin):
"""String method."""
return f'{self.name}'
def save(self, *args, **kwargs):
if not self.pk:
if not self.slug:
slugify_slug = slugify(
f'{self.name} {self.vintage}',
word_boundary=True
)
self.slug = slugify_slug
super(Guide, self).save(*args, **kwargs)
# todo: for test use, use annotation instead
# @property

View File

@ -1,14 +1,15 @@
from django.shortcuts import get_object_or_404
from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField
from slugify import slugify
from collection import models
from review.serializers import ReviewBaseSerializer
from establishment.serializers import EstablishmentGuideElementSerializer
from location import models as location_models
from main.serializers import SiteShortSerializer
from product.serializers import ProductGuideElementSerializer
from utils import exceptions
from utils.methods import string_random
from utils.serializers import TranslatedField
@ -145,6 +146,19 @@ class GuideBaseSerializer(serializers.ModelSerializer):
'vintage': {'required': True},
}
def create(self, validated_data):
"""Overridden create method."""
slug = validated_data.get('slug')
name = validated_data.get('name')
vintage = validated_data.get('vintage')
if not slug:
slug = slugify(f'{name} {vintage}', word_boundary=True)
while models.Guide.objects.filter(slug=slug).exists():
slug = slugify(f'{name} {vintage} {string_random()}', word_boundary=True)
validated_data['slug'] = slug
return super(GuideBaseSerializer, self).create(validated_data)
class GuideElementBaseSerializer(serializers.ModelSerializer):
"""Serializer for model GuideElement."""

View File

@ -102,6 +102,11 @@ class GuideListCreateView(GuideBaseView,
"""View for Guides list for BackOffice users and Guide create."""
filter_class = filters.GuideFilterSet
def create(self, request, *args, **kwargs):
"""Overridden create method."""
super(GuideListCreateView, self).create(request, *args, **kwargs)
return Response(status=status.HTTP_201_CREATED)
class GuideBackOfficeList(BindObjectMixin, GuideBaseView):
"""ViewSet for Guides list for BackOffice users"""

View File

@ -75,17 +75,20 @@ class Country(TranslatedFieldsMixin,
return 'hh:mmA'
@property
def display_calling_code(self) -> str:
def display_calling_code(self) -> list:
"""Return formatted calling code."""
array = []
if self.code and self.calling_code:
# hardcoded calling numbers for Antilles Guyane West Indies islands.
if self.code.lower() == 'aa':
return f"""{[self.CALLING_NUMBER_MASK % i
for i in set(settings.CALLING_CODES_ANTILLES_GUYANE_WEST_INDIES)]}"""
return self.CALLING_NUMBER_MASK % self.calling_code
array.extend([self.CALLING_NUMBER_MASK % i
for i in set(settings.CALLING_CODES_ANTILLES_GUYANE_WEST_INDIES)])
else:
array.append(self.CALLING_NUMBER_MASK % self.calling_code)
return array
@property
def default_calling_code(self):
def default_calling_code(self) -> str:
"""Return default calling code based on phone number."""
if self.code and self.calling_code:
# hardcoded default calling number for Antilles Guyane West Indies islands.

View File

@ -12,7 +12,7 @@ class CountrySerializer(serializers.ModelSerializer):
"""Country serializer."""
name_translated = TranslatedField()
display_calling_code = serializers.CharField(allow_null=True, read_only=True)
display_calling_code = serializers.ListField(allow_null=True, read_only=True)
default_calling_code = serializers.CharField(allow_null=True, read_only=True)
class Meta:

View File

@ -10,7 +10,7 @@ from django.db import connections
from django.db import models
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from mptt.models import MPTTModel, TreeForeignKey
from mptt.models import MPTTModel
from rest_framework import exceptions
from configuration.models import TranslationSettings
@ -216,6 +216,14 @@ class Award(TranslatedFieldsMixin, URLImageMixin, models.Model):
return f'id:{self.id}-{title}'
class AwardTypeQuerySet(models.QuerySet):
"""QuerySet for model AwardType."""
def by_country_code(self, country_code: str):
"""Filter QuerySet by country code."""
return self.filter(country__code=country_code)
class AwardType(models.Model):
"""AwardType model."""
country = models.ForeignKey(
@ -223,6 +231,8 @@ class AwardType(models.Model):
name = models.CharField(_('name'), max_length=255)
old_id = models.IntegerField(null=True, blank=True)
objects = AwardTypeQuerySet.as_manager()
def __str__(self):
return self.name

View File

@ -51,10 +51,15 @@ class AwardRUDView(generics.RetrieveUpdateDestroyAPIView):
class AwardTypesListView(generics.ListAPIView):
"""AwardType List view."""
pagination_class = None
queryset = AwardType.objects.all()
serializer_class = serializers.AwardTypeBaseSerializer
permission_classes = get_permission_classes()
def get_queryset(self):
"""Overridden get_queryset method."""
if hasattr(self, 'request') and hasattr(self.request, 'country_code'):
return AwardType.objects.by_country_code(self.request.country_code)
return AwardType.objects.none()
class ContentTypeView(generics.ListAPIView):
"""ContentType list view"""

View File

@ -57,7 +57,7 @@ def username_validator(username: str) -> bool:
return True
def username_random():
def string_random():
"""Generate random username"""
username = list('{letters}{digits}'.format(
letters=''.join([random.choice(string.ascii_lowercase) for _ in range(4)]),

View File

@ -561,5 +561,5 @@ COUNTRY_CALLING_CODES = {
"aa": 590 # Guyane West Indies
}
CALLING_CODES_ANTILLES_GUYANE_WEST_INDIES = [590, 594, 1758]
CALLING_CODES_ANTILLES_GUYANE_WEST_INDIES = [590, 594, 1758, 596]
DEFAULT_CALLING_CODE_ANTILLES_GUYANE_WEST_INDIES = 590