Skip to content

Commit

Permalink
feat(articles): create article
Browse files Browse the repository at this point in the history
  • Loading branch information
SnyderMbishai committed Dec 10, 2018
1 parent 79d2d28 commit d38c9c3
Show file tree
Hide file tree
Showing 7 changed files with 135 additions and 1 deletion.
3 changes: 3 additions & 0 deletions authors/apps/articles/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from django.contrib import admin

from .models import Article

# Register your models here.
admin.site.register(Article)
26 changes: 25 additions & 1 deletion authors/apps/articles/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
from django.db import models
from django.utils.text import slugify
import uuid

# Create your models here.
from ..authentication.models import User

class Article(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=False)
body = models.TextField()
image = models.URLField(blank=True)
article_slug = models.SlugField(unique=True, editable=False, max_length=255)
author = models.ForeignKey(User, related_name='authorshaven', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.title

def create_slug(self):
slug = slugify(self.title)
while Article.objects.filter(article_slug=slug).exists():
slug = slug + '-' + uuid.uuid4().hex
return slug

def save(self, *args, **kwargs):
self.article_slug = self.create_slug()
super().save(*args,**kwargs)
42 changes: 42 additions & 0 deletions authors/apps/articles/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from rest_framework import serializers

from .models import Article
from ..authentication.serializers import UserSerializer

class ArticleSerializer(serializers.ModelSerializer):
title = serializers.CharField(max_length=200)
description = serializers.CharField()
body = serializers.CharField()
author = serializers.HiddenField(
default = serializers.CurrentUserDefault()
)
# author = UserSerializer(read_only = True)
# author = serializers.SerializerMethodField()

class Meta:
model = Article
fields = '__all__'

def create(self, data):
return Article.objects.create(**data)

def update(self, instance, data):
instance.title = data.get('title', instance.title)
instance.description = data.get('description', instance.description)
instance.body = data.get('body', instance.body)
instance.author_id = data.get('authors_id',instance.author_id)
instance.save()
return instance

def get_author(self,Article):
return Article.author.pk

class AuthorSerializer(serializers.ModelSerializer):
title = serializers.CharField(max_length=200)
description = serializers.CharField()
body = serializers.CharField()
author = UserSerializer(read_only = True)
class Meta:
model = Article
fields = '__all__'

8 changes: 8 additions & 0 deletions authors/apps/articles/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.urls import path

from .views import ArticleAPIView

urlpatterns = [
path('articles/', ArticleAPIView.as_view(), name='articles'),
path('articles/<int:pk>', ArticleAPIView.as_view(), name='articles')
]
55 changes: 55 additions & 0 deletions authors/apps/articles/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,58 @@
from django.shortcuts import render
from rest_framework.views import APIView
from requests.exceptions import HTTPError
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated, IsAuthenticatedOrReadOnly

from .models import Article
from .serializers import ArticleSerializer, AuthorSerializer

# Create your views here.

class ArticleAPIView(APIView):
permission_classes = (IsAuthenticated,IsAuthenticatedOrReadOnly)

def post(self, request):
article_data = request.data.get('article')
context = {'request':request}
serializer = ArticleSerializer(data=article_data, context=context)
serializer.is_valid(raise_exception = True)
if serializer.is_valid():
saved_article = serializer.save()
return Response({"message":"lalalaala"})
return Response({'message':"invalid data"})
# serializer = ArticleSerializer(data=article_data)

# serializer.is_valid(raise_exceptions=True)
# print(serializer.data,"nananan")
# serializer.save()
# return Response({'message':"message"})


def get(self, request, pk=None):
if pk:
article = Article.objects.get(pk=pk)
serializer = AuthorSerializer(article)
return Response({'article':serializer.data})
else:
articles = Article.objects.all()
serializer = AuthorSerializer(articles, many=True)
return Response({'articles': serializer.data})

def put(self, request, pk):
#pk is the primary key
article = Article.objects.get(pk=pk)
data = request.data.get('article')
serializer = ArticleSerializer(instance=article, data=data, partial=True)

if serializer.is_valid():
article = serializer.save()

return Response({'message':"Article has been successfully updated."})

def delete(self, request, pk):
article = Article.objects.get(pk=pk)
article.delete()
return Response({'message':"Successfully deleted."})


1 change: 1 addition & 0 deletions authors/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends',
Expand Down
1 change: 1 addition & 0 deletions authors/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@
path('', schema_view, name='docs'),
path('api/', include(('authors.apps.profiles.urls', 'api-profiles'), namespace='profiles')),
path('oauth/', include('social_django.urls', namespace='social')),
path('api/', include(('authors.apps.articles.urls', 'api-articles'), namespace='articles')),

]

0 comments on commit d38c9c3

Please sign in to comment.