diff --git a/README.md b/README.md index ed0cec1..a19af33 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ From inside the project's folder: - Make migrations: -```bash +``` python manage.py makemigrations core geo companies products history stats python manage.py migrate ``` @@ -45,6 +45,7 @@ To load initial location data use: `python manage.py addgeo` ### User Management Creation: + - endpoint: /api/v1/users/ - method: GET - payload: @@ -57,6 +58,7 @@ Creation: ``` Change password: + - endpoint: api/v1/user/change_password/{user.pk}/ - method: POST - payload: @@ -69,7 +71,6 @@ Change password: ``` Update user profile: -- available for admin - endpoint: api/v1/users// - method: PUT - payload: diff --git a/back_latienda/settings/development.py b/back_latienda/settings/development.py index 3620034..151c75d 100644 --- a/back_latienda/settings/development.py +++ b/back_latienda/settings/development.py @@ -21,7 +21,7 @@ DATABASES = { }, } -MEDIA_ROOT = BASE_DIR + '/../media/' +MEDIA_ROOT = BASE_DIR + '/media/' MEDIA_URL = '/media/' # JWT SETTINGS diff --git a/companies/models.py b/companies/models.py index 73fe716..3fb2ab7 100644 --- a/companies/models.py +++ b/companies/models.py @@ -44,8 +44,7 @@ class Company(models.Model): # internal created = models.DateTimeField('date of creation', auto_now_add=True) updated = models.DateTimeField('date last update', auto_now=True) - creator = models.ForeignKey('core.CustomUser', on_delete=models.DO_NOTHING, null=True, related_name='company_creator') - history = models.ForeignKey('history.HistorySync', on_delete=models.DO_NOTHING, null=True, related_name='company_history') + creator = models.ForeignKey('core.CustomUser', on_delete=models.DO_NOTHING, null=True, related_name='creator') def __str__(self): return self.company_name diff --git a/core/models.py b/core/models.py index 7afba16..6f4da0b 100644 --- a/core/models.py +++ b/core/models.py @@ -49,7 +49,7 @@ class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField('Dirección de email', unique=True) full_name = models.CharField('Nombre completo', max_length=100, blank=True) - role = models.CharField('Rol', choices=ROLES, default=SHOP_USER, max_length=100) + role = models.CharField('Rol', choices=ROLES, default=SHOP_USER, max_length=100, blank=True, null=True) notify = models.BooleanField('Notificar', default=False, null=True) provider = models.CharField('Proveedor', max_length=1000, blank=True, null=True) # red social de registro email_verified = models.BooleanField('Email verificado', default=False, null=True) diff --git a/core/serializers.py b/core/serializers.py index 5f9ec8b..69e4f90 100644 --- a/core/serializers.py +++ b/core/serializers.py @@ -1,30 +1,27 @@ -from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import serializers from . import models class CustomUserSerializer(serializers.ModelSerializer): - password = serializers.CharField(write_only=True, required=True, style={'input_type': 'password'}) + class Meta: model = models.CustomUser - fields = ('id', 'email', 'full_name', 'role', 'password', 'is_active', 'notify') + fields = ('email', 'full_name', 'role', 'is_active') -class CustomUserAdminSerializer(serializers.ModelSerializer): - password = serializers.CharField(write_only=True, required=False, style={'input_type': 'password'}) +class CustomUserReadSerializer(serializers.ModelSerializer): + class Meta: model = models.CustomUser - fields = ('id', 'email', 'full_name', 'role', 'password', 'is_active', 'notify') + fields = ('id', 'email', 'full_name', 'role', 'is_active', 'provider', 'notify') - def update(self, instance, validated_data): - for key, value in validated_data.items(): - instance.__dict__[key] = value - if 'password' in validated_data: - instance.set_password(validated_data['password']) - instance.save() - return instance +class CustomUserWriteSerializer(serializers.ModelSerializer): + + class Meta: + model = models.CustomUser + fields = ('email', 'full_name', 'role', 'password', 'provider') class CreatorSerializer(serializers.ModelSerializer): @@ -34,6 +31,24 @@ class CreatorSerializer(serializers.ModelSerializer): fields = ('email',) +class CustomUserAdminSerializer(serializers.ModelSerializer): + + password = serializers.CharField(write_only=True, required=False, style={'input_type': 'password'}) + + class Meta: + model = models.CustomUser + fields = ('id', 'email', 'full_name', 'role', 'password', 'is_active', 'notify') + + def update(self, instance, validated_data): + + for key, value in validated_data.items(): + instance.__dict__[key] = value + if 'password' in validated_data: + instance.set_password(validated_data['password']) + instance.save() + return instance + + class ChangePasswordSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True) password2 = serializers.CharField(write_only=True, required=True) diff --git a/core/tests.py b/core/tests.py index 1a68f2f..0257ba3 100644 --- a/core/tests.py +++ b/core/tests.py @@ -39,7 +39,7 @@ class CustomUserViewSetTest(APITestCase): # anon user def test_anon_user_can_create_active_instance(self): - """Not logged-in user can create new instance of User, and it's active + """Not logged-in user can create new instance of User but it's inactive """ data = { 'email': 'test@email.com', @@ -428,9 +428,7 @@ class LoadCoopManagerTestCase(APITestCase): # create admin user self.admin_email = f"admin_user@mail.com" self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) - self.admin_user = self.user_factory(email=self.admin_email, is_staff=True, is_active=True) - self.admin_user.set_password(self.password) - self.admin_user.save() + self.admin_user = self.user_factory(email=self.admin_email, password=self.password, is_staff=True, is_active=True) # create regular user self.reg_email = f"user@mail.com" self.user = self.user_factory(email=self.reg_email, is_active=True) diff --git a/core/views.py b/core/views.py index 4176ce6..4dc131c 100644 --- a/core/views.py +++ b/core/views.py @@ -17,7 +17,6 @@ from rest_framework.generics import UpdateAPIView from rest_framework.decorators import api_view, permission_classes from companies.models import Company -from history.models import HistorySync from . import models from . import serializers as core_serializers @@ -43,9 +42,13 @@ class CustomUserViewSet(viewsets.ModelViewSet): model_name = 'custom_user' queryset = models.CustomUser.objects.all() permission_classes = [CustomUserPermissions,] + read_serializer_class = core_serializers.CustomUserReadSerializer + write_serializer_class = core_serializers.CustomUserWriteSerializer def get_serializer_class(self): - if self.action == 'update' and self.request.user.is_staff is False: + if self.action=='create': + return core_serializers.CustomUserWriteSerializer + elif self.action == 'update' and self.request.user.is_staff is False: return core_serializers.UpdateUserSerializer elif self.request.user.is_staff is True: return core_serializers.CustomUserAdminSerializer @@ -60,8 +63,8 @@ class CustomUserViewSet(viewsets.ModelViewSet): """ Create Instance """ - serializer_class = self.get_serializer_class() try: + serializer_class = self.get_serializer_class() serializer = serializer_class( data=request.data, ) @@ -72,7 +75,7 @@ class CustomUserViewSet(viewsets.ModelViewSet): instance.set_password(password) instance.save() - return Response(serializer_class( + return Response(self.read_serializer_class( instance, many=False, context={'request': request}).data, status=status.HTTP_201_CREATED) else: @@ -120,9 +123,6 @@ def load_coop_managers(request): logging.info(f"Reading contents of {csv_file.name}") decoded_file = csv_file.read().decode('utf-8').splitlines() csv_reader = csv.DictReader(decoded_file, delimiter=',') - # create historysync instance - history = HistorySync.objects.create(sync_date=datetime.datetime.now(), quantity=len(decoded_file)) - coop_counter = 0 user_counter = 0 for row in csv_reader: @@ -136,7 +136,6 @@ def load_coop_managers(request): 'short_name': row['nombre-corto'].strip(), 'shop': bool(row['es-tienda'].strip()), 'shop_link': row['url'].strip(), - 'history': history, } coop = Company.objects.create(**coop_data) logging.info(f"Created Coop: {coop_data}") diff --git a/history/models.py b/history/models.py index 0cd313e..e102cb0 100644 --- a/history/models.py +++ b/history/models.py @@ -7,7 +7,7 @@ class HistorySync(models.Model): Keeps an historic record of the importation of products for a company """ - company = models.ForeignKey('companies.Company', on_delete=models.DO_NOTHING, null=True, related_name='history_company') + company = models.ForeignKey('companies.Company', on_delete=models.DO_NOTHING, null=True) rss_url = models.URLField('URL del feed', null=True, blank=True) sync_date = models.DateTimeField('Fecha de lanzamiento', null=True) result = models.TextField('Resultado', null=True, blank=True) diff --git a/requirements.txt b/requirements.txt index 9ed18b0..b13037e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,4 +10,3 @@ django-cors-headers==3.5.0 django-taggit-serializer==0.1.7 django-tagulous==1.1.0 Pillow==8.1.0 -requests==2.25.1