-
Notifications
You must be signed in to change notification settings - Fork 65
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
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мне кажется ты не совсем понял того чего я хочу добиться как разработчик (владелец компании) ты должен
- создать свою компанию post /company/
- редактировать данные компании put /company/
- удалить компанию delete /company/
- посмотреть свою компанию get /company/
В твоем же случае ты показываешь список компаний, потом обращаешься к каждой по title в этом случае это не нужно,если будет всем необходим такой функционал то мы просто сделаем просмотр для всех пользователей в модуле common.
http_method_names = ["get", "post", "put", "delete"] | ||
queryset = Company.objects.all() | ||
serializer_class = CompanySerializer | ||
permission_classes = (IsAdminOrOwnerCompany,) |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
За проверки все отвечают permissions, нужно внимательнее их определить
5c0cebb
to
72c4879
Compare
There was a problem hiding this 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("Пользователь удалён"), |
There was a problem hiding this comment.
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("Компания не найден"), |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Пробелы лишние убери
Перед мерджем хотел бы обсудить следущие вопросы:
При запросах поле created_by - является обязательным, и в форме запроса оно отображается, но по нашему функционалу заполняется автоматически. Отсюда вопрос, можно будет его на фронте скрыть, и если нет то хотелось бы совет, как я могу это реализовать
В методе пост я делаю проверку на соотвествие пользователя классу CompanyUser, которая вызывает ошибку 403, ее можно не проводить, тогда будет возникать ошибка 400, вызываемая несоотвествием поля уникакльности
В целом я провожу несколько проверок на instance пользователя, в разных http методах, мб вывести это в отдельный метод ?
Функионал для админа пока не готов, поэтому некоторые тесты закоментил