...
 
Commits (3)
# Generated by Django 2.2.2 on 2019-06-12 11:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='count',
field=models.IntegerField(blank=True, null=True),
),
]
# Generated by Django 2.2.2 on 2019-06-12 11:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_post_count'),
]
operations = [
migrations.RenameField(
model_name='post',
old_name='count',
new_name='likes_counter',
),
]
# Generated by Django 2.2.2 on 2019-06-12 15:24
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_auto_20190612_1112'),
]
operations = [
migrations.AlterField(
model_name='post',
name='created_at',
field=models.DateTimeField(default=datetime.datetime.now),
),
]
# Generated by Django 2.2.2 on 2019-06-12 15:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_auto_20190612_1524'),
]
operations = [
migrations.AlterField(
model_name='post',
name='created_at',
field=models.DateTimeField(auto_now_add=True),
),
]
from django.db import models
# Create your models here.
# Create your models here
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
......@@ -8,8 +10,9 @@ class Post(models.Model):
on_delete=models.CASCADE,
)
body = models.TextField()
likes_counter = models.IntegerField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
\ No newline at end of file
return self.title
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'author_id', 'title', 'body', 'created_at']
# read only = cannot be modified:
# read_only_fields = ['id', 'first_name']
# extra_kwargs = {
# 'password': {
# # write only (cant be read afterwards)
# 'write_only': True
# }
# }
from django.urls import path
from blog.views import (BlogPostsAPIView,
BlogCreatePostAPIView,
UserListPostsAPIView,
BlogPostRetrieveAPIView,
BlogPostDeleteAPIView,
BlogPostUpdateAPIView)
urlpatterns = [
path('', BlogPostsAPIView.as_view()),
path('new-post/', BlogCreatePostAPIView.as_view()),
path('posts-by-user-id/<author_id>/', UserListPostsAPIView.as_view()),
path('post-by-post-id/<id>/', BlogPostRetrieveAPIView.as_view()),
path('delete-post-by-post-id/<id>/', BlogPostDeleteAPIView.as_view()),
path('update-post-by-post-id/<id>/', BlogPostUpdateAPIView.as_view()),
]
from rest_framework import generics
# import the table from the Model
from .models import Post
from .serializers import PostSerializer
'''
Generics Views
'''
class BlogPostsAPIView(generics.ListAPIView):
permission_classes = []
authentication_classes = []
queryset = Post.objects.all()
serializer_class = PostSerializer
class BlogCreatePostAPIView(generics.CreateAPIView):
permission_classes = []
authentication_classes = []
queryset = Post.objects.all()
serializer_class = PostSerializer
class UserListPostsAPIView(generics.ListAPIView):
permission_classes = []
authentication_classes = []
queryset = Post.objects.all()
serializer_class = PostSerializer
def get_queryset(self, *args, **kwargs):
kwargs = self.kwargs
kw_id = kwargs.get('author_id')
return self.queryset.filter(author_id=kw_id)
class BlogPostRetrieveAPIView(generics.RetrieveAPIView):
permission_classes = []
authentication_classes = []
queryset = Post.objects.all()
serializer_class = PostSerializer
lookup_field = 'id'
class BlogPostUpdateAPIView(generics.UpdateAPIView):
permission_classes = []
authentication_classes = []
queryset = Post.objects.all()
serializer_class = PostSerializer
lookup_field = 'id'
class BlogPostDeleteAPIView(generics.DestroyAPIView):
permission_classes = []
authentication_classes = []
queryset = Post.objects.all()
serializer_class = PostSerializer
lookup_field = 'id'
'''
Without Serializer
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View
def view_post_details(response):
# Store the field in a variable post from a Django query
post = Post.objects.values('author', 'title', 'body', 'created_at').all()
# to view all fields
# post = Post.objects.values().all()
# convert it to a list
post = list(post)
return JsonResponse(post, safe=False)
'''
'''
API View
from rest_framework.views import APIView
from rest_framework.response import Response
class PostListSearchAPIView(APIView):
permission_classes = []
authentication_classes = []
@staticmethod
def get(request, format = None):
qs = Post.objects.all()
# type(qs) --> <class 'django.db.models.query.QuerySet'>
serializer = PostSerializer(qs, many=True)
# type(serializer) --> <class 'rest_framework.serializers.ListSerializer'>
# Create your views here.
return Response(serializer.data)
'''
\ No newline at end of file
......@@ -39,6 +39,7 @@ INSTALLED_APPS = [
'django.contrib.staticfiles',
'blog',
'rest_framework',
]
MIDDLEWARE = [
......@@ -93,6 +94,19 @@ DATABASES = {
}
}
### OR
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql_psycopg2',
# 'NAME': os.environ.get('POSTGRES_NAME'),
# 'PORT': os.environ.get('POSTGRES_PORT'),
# 'HOST': 'postgres',
# 'PASSWORD': 'postgres',
# 'USER': 'postgres'
# }
# }
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
......@@ -127,7 +141,16 @@ USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
# REST_FRAMEWORK = {
# # Use Django's standard `django.contrib.auth` permissions,
# # or allow read-only access for unauthenticated users.
# 'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
# ]
# }
......@@ -14,8 +14,13 @@ Including another URLconf
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
# Django REST
# path('api-auth/', include('rest_framework.urls')),
]
......@@ -5,3 +5,7 @@ dependencies:
- pip:
- django==2.2.2
- flake8
# Django Rest Framework packages
- djangorestframework
- markdown # Markdown support for the browsable API.
- django-filter # Filtering support
Create Django Project in Docker
1. Basic Setup
- Create your project on gitlab
- Create a folder for the repo on local
......@@ -157,7 +156,6 @@ INSTALLED_APPS = [
]
13. Create a model at <app name> / models -->
example:
class Post(models.Model):
......@@ -179,21 +177,99 @@ python manage.py makemigrations
python manage.py migrate
15. Check that the table has created -->
15. Check that the table has been created -->
table name = <app name>_<model class name in lowercase>
ex: blog_post
16. Add it to the admin
16. If you want to give access to the admin,
Go to app directory / admin.py -->
admin.site.register(<model class name>)
ex: admin.site.register(Post)
17. Create the views inside the app / views.py
18. Create a urls.py inside the app directory to include the app's views -->
<app name> / urls.py
urlpatterns = [
path('', view_all), # name='get-all-posts'
]
19. Include in django's urls.py the path of the app's urls -->
<django project > / urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
]
#################################################################
Create Django REST API
1. Install packages if not already in the requirements.yml -->
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
2. Add 'rest_framework' to your INSTALLED_APPS settings.py -->
INSTALLED_APPS = (
...
'rest_framework',
)
3. If you're intending to use the browsable API you'll probably also want to add REST framework's login
and logout views. Add the following to your root urls.py file -->
urlpatterns = [
...
path('api-auth/', include('rest_framework.urls')),
]
4. Any global settings for a REST framework API are kept in a single
configuration dictionary named REST_FRAMEWORK.
Add the following to the settings.py module -->
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
5. Create a serializers.py in <app name> directory -->
blog/serializers.py -->
from rest_framework import serializers
from .models import <Model class>
class <model class>Serializer(serializers.ModelSerializer):
class Meta:
model = <model class>
fields = ['author', 'title', 'body', 'created_at']
6. Create the Api View in <app name>/views.py
7. Map the Api View in urls.py <app name>/urls.py
8. Check that the app's urls are mapped in projects urls --> app/project/urls.py
############ CREATE SERIALIZER MODULE
############ CREATE GENERICS VIEWS
############ EXTEND USERS TABLE
HOW TO CHANGE THE TIMEZONE ?? --> use local time from python library
WHAT IS META IN MODEL CLASS ??
WHAT IS from django.contrib.auth import get_user_model ??
WHAT IS THE DIFFERENCE BETWEEN VIEW AND GENERIC VIEW?? --> There are different classes, Generic has more packages