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

Solution #714

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions cinema/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ def validate_ticket(row, seat, cinema_hall, error_to_raise):
raise error_to_raise(
{
ticket_attr_name: f"{ticket_attr_name} number "
f"must be in available range: "
f"(1, {cinema_hall_attr_name}): "
f"(1, {count_attrs})"
f"must be in available range: "
f"(1, {cinema_hall_attr_name}): "
f"(1, {count_attrs})"
}
)

Expand All @@ -110,11 +110,11 @@ def clean(self):
)

def save(
self,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
self,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
self.full_clean()
return super(Ticket, self).save(
Expand Down
8 changes: 8 additions & 0 deletions cinema/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from rest_framework.permissions import BasePermission, SAFE_METHODS


class IsAdminOrIfAuthenticatedReadOnly(BasePermission):
def has_permission(self, request, view):
return request.user.is_staff or (
request.user.is_authenticated and request.method in SAFE_METHODS
)
18 changes: 16 additions & 2 deletions cinema/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,14 @@ class Meta:
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = ("id", "title", "description", "duration", "genres", "actors")
fields = (
"id",
"title",
"description",
"duration",
"genres",
"actors"
)


class MovieListSerializer(MovieSerializer):
Expand All @@ -51,7 +58,14 @@ class MovieDetailSerializer(MovieSerializer):

class Meta:
model = Movie
fields = ("id", "title", "description", "duration", "genres", "actors")
fields = (
"id",
"title",
"description",
"duration",
"genres",
"actors"
)


class MovieSessionSerializer(serializers.ModelSerializer):
Expand Down
12 changes: 3 additions & 9 deletions cinema/tests/test_movie_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ def test_get_movies(self):
def test_retrieve_movie(self):
movie = sample_movie()
movie.genres.add(Genre.objects.create(name="Genre"))
movie.actors.add(
Actor.objects.create(first_name="Actor", last_name="Last")
)
movie.actors.add(Actor.objects.create(first_name="Actor", last_name="Last"))

url = detail_url(movie.id)
response = self.client.get(url)
Expand Down Expand Up @@ -114,16 +112,12 @@ def test_put_movie(self):
}

response = self.client.put(url, payload)
self.assertEqual(
response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED
)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)

def test_delete_movie(self):
movie = sample_movie()

url = detail_url(movie.id)
response = self.client.delete(url)

self.assertEqual(
response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED
)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
42 changes: 33 additions & 9 deletions cinema/views.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from datetime import datetime

from django.db.models import F, Count
from rest_framework import viewsets
from rest_framework import viewsets, mixins
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated

from cinema.models import Genre, Actor, CinemaHall, Movie, MovieSession, Order

Expand All @@ -21,22 +22,39 @@
)


class GenreViewSet(viewsets.ModelViewSet):
class GenreViewSet(
mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet
):
queryset = Genre.objects.all()
serializer_class = GenreSerializer


class ActorViewSet(viewsets.ModelViewSet):
class ActorViewSet(
mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet
):
queryset = Actor.objects.all()
serializer_class = ActorSerializer


class CinemaHallViewSet(viewsets.ModelViewSet):
class CinemaHallViewSet(
mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet
):
queryset = CinemaHall.objects.all()
serializer_class = CinemaHallSerializer


class MovieViewSet(viewsets.ModelViewSet):
class MovieViewSet(
mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet
):
queryset = Movie.objects.prefetch_related("genres", "actors")
serializer_class = MovieSerializer

Expand Down Expand Up @@ -81,9 +99,10 @@ class MovieSessionViewSet(viewsets.ModelViewSet):
MovieSession.objects.all()
.select_related("movie", "cinema_hall")
.annotate(
tickets_available=F("cinema_hall__rows")
* F("cinema_hall__seats_in_row")
- Count("tickets")
tickets_available=(
F("cinema_hall__rows") * F("cinema_hall__seats_in_row")
- Count("tickets")
)
)
)
serializer_class = MovieSessionSerializer
Expand Down Expand Up @@ -118,12 +137,17 @@ class OrderPagination(PageNumberPagination):
max_page_size = 100


class OrderViewSet(viewsets.ModelViewSet):
class OrderViewSet(
mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet
):
queryset = Order.objects.prefetch_related(
"tickets__movie_session__movie", "tickets__movie_session__cinema_hall"
)
serializer_class = OrderSerializer
pagination_class = OrderPagination
permission_classes = [IsAuthenticated]

def get_queryset(self):
return Order.objects.filter(user=self.request.user)
Expand Down
21 changes: 13 additions & 8 deletions cinema_service/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

Expand Down Expand Up @@ -80,7 +79,6 @@

WSGI_APPLICATION = "cinema_service.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

Expand All @@ -91,26 +89,25 @@
}
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation."
"UserAttributeSimilarityValidator",
"UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation."
"MinimumLengthValidator",
"MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation."
"CommonPasswordValidator",
"CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation."
"NumericPasswordValidator",
"NumericPasswordValidator",
},
]

Expand All @@ -127,7 +124,6 @@

USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

Expand All @@ -137,3 +133,12 @@
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"cinema.permissions.IsAdminOrIfAuthenticatedReadOnly",
],
}
1 change: 1 addition & 0 deletions cinema_service/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
urlpatterns = [
path("admin/", admin.site.urls),
path("api/cinema/", include("cinema.urls", namespace="cinema")),
path("api/user/", include("user.urls", namespace="user")),
path("__debug__/", include("debug_toolbar.urls")),
]
24 changes: 23 additions & 1 deletion user/serializers.py
Original file line number Diff line number Diff line change
@@ -1 +1,23 @@
# write your code here
from django.contrib.auth import get_user_model
from rest_framework import serializers


class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ["id", "username", "email", "password", "is_staff"]
read_only_fields = ["id", "is_staff"]
extra_kwargs = {"password": {"write_only": True, "min_length": 5}}

def create(self, validated_data):
return get_user_model().objects.create_user(**validated_data)

def update(self, instance, validated_data):
password = validated_data.pop("password", None)
user = super().update(instance, validated_data)

if password:
user.set_password(password)
user.save()

return user
12 changes: 11 additions & 1 deletion user/urls.py
Original file line number Diff line number Diff line change
@@ -1 +1,11 @@
# write your code here
from django.urls import path

from user.views import CreateUserView, LoginUserView, ManageUserView

urlpatterns = [
path("register/", CreateUserView.as_view(), name="create"),
path("login/", LoginUserView.as_view(), name="login"),
path("me/", ManageUserView.as_view(), name="manage"),
]

app_name = "user"
23 changes: 22 additions & 1 deletion user/views.py
Original file line number Diff line number Diff line change
@@ -1 +1,22 @@
# write your code here
from rest_framework import generics
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.permissions import IsAuthenticated, AllowAny

from user.serializers import UserSerializer


class CreateUserView(generics.CreateAPIView):
serializer_class = UserSerializer
permission_classes = [AllowAny]


class LoginUserView(ObtainAuthToken):
permission_classes = [AllowAny]


class ManageUserView(generics.RetrieveUpdateAPIView):
serializer_class = UserSerializer
permission_classes = [IsAuthenticated]

def get_object(self):
return self.request.user
Loading