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

DRF COURSE REFERENCE MATERIAL. #17

Open
wants to merge 1 commit into
base: module_1
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
Empty file added backend/core/__init__.py
Empty file.
7 changes: 7 additions & 0 deletions backend/core/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.contrib import admin
from .models import Contact


@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'description', 'email')
6 changes: 6 additions & 0 deletions backend/core/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'core'
33 changes: 33 additions & 0 deletions backend/core/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Generated by Django 4.1.3 on 2023-12-29 20:32

from django.db import migrations, models
import django_extensions.db.fields
import uuid


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('created', django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, verbose_name='created')),
('modified', django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified')),
('title', models.CharField(max_length=255, verbose_name='title')),
('description', models.TextField(blank=True, null=True, verbose_name='description')),
('status', models.IntegerField(choices=[(0, 'Inactive'), (1, 'Active')], default=1, verbose_name='status')),
('activate_date', models.DateTimeField(blank=True, help_text='keep empty for an immediate activation', null=True)),
('deactivate_date', models.DateTimeField(blank=True, help_text='keep empty for indefinite activation', null=True)),
('email', models.EmailField(max_length=254, verbose_name='Email')),
],
options={
'verbose_name_plural': 'Contacts',
},
),
]
Empty file.
22 changes: 22 additions & 0 deletions backend/core/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from django.db import models
from utils.model_abstracts import Model
from django_extensions.db.models import (
TimeStampedModel, # fields like created
ActivatorModel, # status field, activated date and deactivated date
TitleDescriptionModel # 2 text fields (char)
)

class Contact(
TimeStampedModel,
ActivatorModel,
TitleDescriptionModel,
Model
):

class Meta:
verbose_name_plural = "Contacts"

email = models.EmailField(verbose_name="Email") #email field

def __str__(self):
return f'{self.title}'
19 changes: 19 additions & 0 deletions backend/core/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from . import models
from rest_framework import serializers
from rest_framework.fields import CharField, EmailField



class ContactSerializer(serializers.ModelSerializer):

name = CharField(source="title", required=True)
message = CharField(source="description", required=True)
email = EmailField(required=True)

class Meta:
model = models.Contact
fields = (
'name',
'email',
'message'
)
93 changes: 93 additions & 0 deletions backend/core/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
from . models import Contact
from rest_framework.test import APIClient
from rest_framework.test import APITestCase
from rest_framework import status



class ContactTestCase(APITestCase):

"""
Test suite for Contact
"""
def setUp(self):
self.client = APIClient()
self.data = {
"name": "Billy Smith",
"message": "This is a test message",
"email": "[email protected]"
}
self.url = "/contact/"

def test_create_contact(self):
'''
test ContactViewSet create method
'''
data = self.data
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Contact.objects.count(), 1)
self.assertEqual(Contact.objects.get().title, "Billy Smith")

def test_create_contact_without_name(self):
'''
test ContactViewSet create method when name is not in data
'''
data = self.data
data.pop("name")
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_create_contact_when_name_equals_blank(self):
'''
test ContactViewSet create method when name is blank
'''
data = self.data
data["name"] = ""
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_create_contact_without_message(self):
'''
test ContactViewSet create method when message is not in data
'''
data = self.data
data.pop("message")
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_create_contact_when_message_equals_blank(self):
'''
test ContactViewSet create method when message is blank
'''
data = self.data
data["message"] = ""
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_create_contact_without_email(self):
'''
test ContactViewSet create method when email is not in data
'''
data = self.data
data.pop("email")
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_create_contact_when_email_equals_blank(self):
'''
test ContactViewSet create method when email is blank
'''
data = self.data
data["email"] = ""
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def test_create_contact_when_email_equals_non_email(self):
'''
test ContactViewSet create method when email is not email
'''
data = self.data
data["email"] = "test"
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
37 changes: 37 additions & 0 deletions backend/core/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from json import JSONDecodeError
from django.http import JsonResponse
from .serializers import ContactSerializer
from rest_framework.parsers import JSONParser
from rest_framework import views, status
from rest_framework.response import Response



class ContactAPIView(views.APIView):
"""
A simple APIView for creating contact entires.
"""
serializer_class = ContactSerializer

def get_serializer_context(self):
return {
'request': self.request,
'format': self.format_kwarg,
'view': self
}

def get_serializer(self, *args, **kwargs):
kwargs['context'] = self.get_serializer_context()
return self.serializer_class(*args, **kwargs)

def post(self, request):
try:
data = JSONParser().parse(request)
serializer = ContactSerializer(data=data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
except JSONDecodeError:
return JsonResponse({"result": "error","message": "Json decoding error"}, status= 400)
4 changes: 2 additions & 2 deletions backend/docker/docker_files/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ ENV PYTHONDONTWRITEBYTECODE 1

RUN set -e; \
apt-get update ;\
apt-get -y install netcat ;\
apt-get -y install netcat-traditional ;\
apt-get -y install gettext ;

RUN mkdir /code
Expand All @@ -15,7 +15,7 @@ WORKDIR /code
RUN set -e; \
/usr/local/bin/python -m pip install --upgrade pip ;\
python -m pip install -r /code/requirements.txt ;\
chmod +x /code/docker/entrypoints/entrypoint.sh ;
chmod +r,+x /code/docker/entrypoints/entrypoint.sh ;

EXPOSE 8000
ENTRYPOINT ["/code/docker/entrypoints/entrypoint.sh"]
Expand Down
2 changes: 1 addition & 1 deletion backend/docker/docker_files/Dockerfile_app
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ ENV PYTHONDONTWRITEBYTECODE 1

RUN set -e; \
apt-get update ;\
apt-get -y install netcat ;\
apt-get -y install netcat-traditional ;\
apt-get -y install gettext ;\
apt-get -y install httpie; \
pip install --upgrade pip \
Expand Down
Empty file added backend/drf_course/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions backend/drf_course/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for drf_course project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'drf_course.settings')

application = get_asgi_application()
Loading