Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Users | post/put/delete company functional for developer #332

Merged
merged 6 commits into from
Jun 28, 2023

Conversation

Roman-Zhirovskis
Copy link

Перед мерджем хотел бы обсудить следущие вопросы:

При запросах поле created_by - является обязательным, и в форме запроса оно отображается, но по нашему функционалу заполняется автоматически. Отсюда вопрос, можно будет его на фронте скрыть, и если нет то хотелось бы совет, как я могу это реализовать

В методе пост я делаю проверку на соотвествие пользователя классу CompanyUser, которая вызывает ошибку 403, ее можно не проводить, тогда будет возникать ошибка 400, вызываемая несоотвествием поля уникакльности

В целом я провожу несколько проверок на instance пользователя, в разных http методах, мб вывести это в отдельный метод ?

Функионал для админа пока не готов, поэтому некоторые тесты закоментил

Copy link
Collaborator

@gravity48 gravity48 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне кажется ты не совсем понял того чего я хочу добиться как разработчик (владелец компании) ты должен

  1. создать свою компанию post /company/
  2. редактировать данные компании put /company/
  3. удалить компанию delete /company/
  4. посмотреть свою компанию get /company/

В твоем же случае ты показываешь список компаний, потом обращаешься к каждой по title в этом случае это не нужно,если будет всем необходим такой функционал то мы просто сделаем просмотр для всех пользователей в модуле common.

http_method_names = ["get", "post", "put", "delete"]
queryset = Company.objects.all()
serializer_class = CompanySerializer
permission_classes = (IsAdminOrOwnerCompany,)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если ты переопределяешь метод get_permissions, не вводи в заблуждение указанием permission_classes. C этими пермишенами косяк, я исправлю, их быть не должны, все основные permissions находятся в модуле common.permissions

),
)
def get(self, request, title=None, format=None):
print(request.method.lower())
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Все дебаги убираем

def get(self, request, title=None, format=None):
print(request.method.lower())
if title:
company = Company.objects.get(title=title)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему здесь не использовать метод get_object_or_404?

)
def get(self, request, title=None, format=None):
print(request.method.lower())
if title:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай логику разделим, если pk есть то это будет отдельный метод как например реализован retrieve

)
def post(self, request, *args, **kwargs):
user = request.user
if not isinstance(user, CompanyUser):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У тебя за это должны отвечать permissions. Попробуй опеределить подробнее permissions в методе get_permissions

)
def put(self, request, title, format=None):
company = get_object_or_404(self.queryset, title=title)
if company.created_by != request.user:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

За проверки все отвечают permissions, нужно внимательнее их определить

Copy link
Collaborator

@gravity48 gravity48 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправь связь с моделью Company на one2one, сделай rebase

operation_description="Удалить компанию",
tags=["Разработчик", "Административная панель разработчика"],
responses={
204: openapi.Response("Пользователь удалён"),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправь что компания удалена

responses={
204: openapi.Response("Пользователь удалён"),
403: openapi.Response("Отсутствуют права на удаление"),
404: openapi.Response("Компания не найден"),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Компания не создана

company = get_object_or_404(Company, created_by=user)
company.delete()

return Response(status=status.HTTP_204_NO_CONTENT)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пробелы лишние убери

@gravity48 gravity48 merged commit c33b053 into DJWOMS:users Jun 28, 2023
1 check passed
@Roman-Zhirovskis Roman-Zhirovskis deleted the romandev branch June 29, 2023 07:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants