Skip to content

Commit

Permalink
fix(articles errors):Refactor articles and heroku deployment
Browse files Browse the repository at this point in the history
- adds user profile details to the return responses
- works a robust slug implementation
- edit model to allow unique slugs
- Refactored code to be more Django
- added individual migration files in procfile
- streamlined the requirements.txt file
- removed unused functions

[Delivers #162694397]
  • Loading branch information
GransonO committed Dec 18, 2018
1 parent 946a579 commit fc95675
Show file tree
Hide file tree
Showing 20 changed files with 228 additions and 331 deletions.
19 changes: 7 additions & 12 deletions authors/apps/articles/models.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
from django.db import models
from authors.apps.authentication.models import User
from authors.apps.profiles.models import Profile

# Create your models here.


class Articles(models.Model):
""" Model for all articles """
slug = models.SlugField(max_length=250, default='non')
title = models.CharField(max_length=50, default='non')
description = models.CharField(max_length=250, default='non')
body = models.CharField(max_length=550, default='non')
tagList = models.CharField(max_length=50,
default='non') # ["dragons", "training"],
slug = models.SlugField(unique=True, max_length=250)
title = models.CharField(max_length=250)
description = models.CharField(max_length=350)
body = models.TextField()
tagList = models.CharField(max_length=200)
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
favorited = models.BooleanField(default=False)
favoritesCount = models.IntegerField(default=0)
readtime = models.IntegerField(default=0)
author = models.ForeignKey(User, default=0, on_delete=models.CASCADE)

def __str__(self):
""" String representation of db object """
return ' {}: {}'.format(self.id, self.slug)
author = models.ForeignKey(Profile, on_delete=models.CASCADE)

class Meta:
ordering = ["-createdAt", "-updatedAt"]
160 changes: 27 additions & 133 deletions authors/apps/articles/serializers.py
Original file line number Diff line number Diff line change
@@ -1,145 +1,39 @@
from rest_framework import serializers
import logging

from .models import Articles
from authors.apps.authentication.models import User
from authors.apps.profiles.serializers import BasicProfileSerializer

logger = logging.getLogger(__file__)


class ArticleSerializer(serializers.ModelSerializer):

author = serializers.SerializerMethodField()

class Meta:
model = Articles
fields = ("__all__")

@staticmethod
def get_all_objects():
articles = Articles.objects.all()
user = AuthorSerializer()

articles_list = []
for article in articles:
article = {
"slug": article.slug,
"title": article.title,
"description": article.description,
"body": article.body,
"tagList": article.tagList.split(","),
"createdAt": article.createdAt,
"updatedAt": article.updatedAt,
"favorited": article.favorited,
"favoritesCount": article.favoritesCount,
"author": user.get_author_objects(article.author.pk)
}
articles_list.append(article)

return (articles_list)

def get_specific_objects(self, slug):
self.article = Articles.objects.get(slug=slug)
user = AuthorSerializer()
article = {
"slug": self.article.slug,
"title": self.article.title,
"description": self.article.description,
"body": self.article.body,
"tagList": self.article.tagList.split(","),
"createdAt": self.article.createdAt,
"updatedAt": self.article.updatedAt,
"favorited": self.article.favorited,
"favoritesCount": self.article.favoritesCount,
"author": user.get_author_objects(self.article.author.pk)
}

return (article)

def posting_articles(self, value): # dictionary passed from view
author_details = self.get_authors_object(
value['author']) # get user object
article_slug = self.slugify_string(value['title'])
read_time = self.readTime(value['body'])

self.new_article = Articles(
slug=article_slug,
title=value['title'],
description=value['description'],
body=value['body'],
tagList=value['tagList'],
author=author_details,
readtime=read_time)

try:
self.new_article.save()
return (self.get_all_objects())

except Exception as What_is_this:
print('error {}'.format(What_is_this))
return ("Could not post")

def get_authors_object(self, name):
user_details = User.objects.get(username=name)
return user_details

def slugify_string(self, string):
string = string.lower()
processed_slug = string.replace(" ", "-")

db_check = Articles.objects.filter(slug=processed_slug).count()
if db_check < 1: # Slug exists in DB
return processed_slug

else:
new_slug = '{}*'.format(processed_slug)
return self.slugify_string(new_slug)

def readTime(self, story):
story_list = story.split(" ")
resolved_time = (len(story_list)) / 200
read_time = round(resolved_time)
return read_time

def updateArticle(self, value, passed_slug):
try:
Articles.objects.filter(
slug=passed_slug).update(
slug=self.slugify_string(
value['title']),
title=value['title'],
description=value['description'],
body=value['body'],
tagList=value['tagList'],
readtime=self.readTime(
value['body']))
return ('Update was successful, Title: {}'.format(value['title']))

except Exception as What_is_this:
print('Received error is : {}'.format(What_is_this))
return ('error')

def deleteArticle(self, passed_slug):
try:
deleted_article = Articles.objects.get(slug=passed_slug)
title = deleted_article.title
deleted_article.delete()
return ('Article title: {} deleted successfully'.format(title))

except Exception as What_is_this:
print('Received error is : {}'.format(What_is_this))
return ("Article does not exist")


class AuthorSerializer(serializers.ModelSerializer):
fields = "__all__"

def author_details(self, obj):
user = self.context["user"]

# logger.error(user_context)
return user

def get_author(self, obj):
author_profile = obj.author
serialized = BasicProfileSerializer(
author_profile, context=self.context)

return serialized.data


class CreateArticleSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = ("__all__")

def get_author_objects(self, id):
user = User.objects.get(pk=id)

author = {
'username': user.username,
'bio': 'profile.bio',
'image': 'profile.image',
# 'following': profile.following
}
return (author)
model = Articles
fields = "__all__"


class BasicArticleSerializer(serializers.ModelSerializer):
Expand Down
8 changes: 4 additions & 4 deletions authors/apps/articles/tests/endpoints/test_delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from django.contrib.auth import get_user_model

from authors.apps.articles.models import Articles
from authors.apps.authentication.models import User
from authors.apps.profiles.models import Profile


class TestGetEndpoint(APITestCase):
Expand All @@ -31,7 +31,7 @@ def setUp(self):
tagList=self.tagList,
favorited=True,
favoritesCount=self.favoritesCount,
author=User.objects.get(username=self.author))
author=Profile.objects.get(username=self.author))
self.article.save()

def test_delArticle_status(self):
Expand All @@ -40,7 +40,7 @@ def test_delArticle_status(self):
response = self.client.delete(url)
response.render()
self.assertIn(
b'Article title: Life Love and Death deleted successfully',
b'Article life-love-death deleted successfully',
response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)

Expand All @@ -49,7 +49,7 @@ def test_wrong_status(self):
self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
response = self.client.delete(url)
response.render()
self.assertIn(b'Article does not exist', response.content)
self.assertIn(b'Could not find that article', response.content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

def get_user_token(self):
Expand Down
4 changes: 2 additions & 2 deletions authors/apps/articles/tests/endpoints/test_get.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from django.contrib.auth import get_user_model

from authors.apps.articles.models import Articles
from authors.apps.authentication.models import User
from authors.apps.profiles.models import Profile


class TestGetEndpoint(APITestCase):
Expand All @@ -32,7 +32,7 @@ def setUp(self):
tagList=self.tagList,
favorited=self.favorited,
favoritesCount=self.favoritesCount,
author=User.objects.get(username=self.author))
author=Profile.objects.get(username=self.author))
self.article.save()

def test_get_all_articles(self):
Expand Down
4 changes: 1 addition & 3 deletions authors/apps/articles/tests/endpoints/test_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@ def setUp(self):
self.token = self.get_user_token()

self.data = {
"slug": "posting_test",
"title": "Posting Test",
"description": "this is a posting test",
"body": "The test was successful",
"tagList": "live again",
"author": 'TestAuthor'
"tagList": "live again"
}

def test_postArticle_status(self):
Expand Down
11 changes: 5 additions & 6 deletions authors/apps/articles/tests/endpoints/test_put.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from django.contrib.auth import get_user_model

from authors.apps.articles.models import Articles
from authors.apps.authentication.models import User
from authors.apps.profiles.models import Profile


class TestGetEndpoint(APITestCase):
Expand All @@ -20,8 +20,7 @@ def setUp(self):
"title": "Posting Test",
"description": "this is a posting test",
"body": "The test was successful",
"tagList": "live again",
"author": "TestAuthor"
"tagList": "live again"
}
self.all_setup()

Expand All @@ -30,7 +29,7 @@ def test_putArticle_status(self):
url = reverse('articleSpecific', kwargs={'slug': 'life-love-death'})
response = self.client.put(url, self.data, format='json')
response.render()
self.assertIn(b'Update was successful', response.content)
self.assertIn(b'Update successful', response.content)

def test_putArticle_no_token_provided(self):
url = reverse('articleSpecific', kwargs={'slug': 'life-love-death'})
Expand All @@ -51,7 +50,7 @@ def test_get_specific_article(self):
self.assertIn(b"Life Love and Death", response.content)
self.assertIn(b"What is life?", response.content)
self.assertIn(b"This is the real life body.", response.content)
self.assertIn(b"[\"life\",\"love\",\"death\"]", response.content)
self.assertIn(b"life,love,death", response.content)
self.assertIn(b"4", response.content)

def all_setup(self):
Expand All @@ -73,7 +72,7 @@ def all_setup(self):
tagList=self.tagList,
favorited=self.favorited,
favoritesCount=self.favoritesCount,
author=User.objects.get(username=self.author))
author=Profile.objects.get(username=self.author))

self.article.save()

Expand Down
4 changes: 2 additions & 2 deletions authors/apps/articles/tests/models/test_add_article.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from rest_framework.test import APITestCase
from django.urls import reverse

from authors.apps.authentication.models import User
from authors.apps.profiles.models import Profile
from authors.apps.articles.models import Articles

# Create your tests here.
Expand Down Expand Up @@ -46,7 +46,7 @@ def setUp(self):
tagList=self.tagList,
favorited=self.favorited,
favoritesCount=self.favoritesCount,
author=User.objects.get(
author=Profile.objects.get(
username=self.author))

def test_add_article(self):
Expand Down
6 changes: 3 additions & 3 deletions authors/apps/articles/tests/models/test_deletearticle.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from rest_framework.test import APITestCase
from django.urls import reverse

from authors.apps.authentication.models import User
from authors.apps.profiles.models import Profile
from authors.apps.articles.models import Articles


Expand Down Expand Up @@ -46,7 +46,7 @@ def setUp(self):
tagList=self.tagList,
favorited=self.favorited,
favoritesCount=self.favoritesCount,
author=User.objects.get(
author=Profile.objects.get(
username=self.author))

# Second Item
Expand All @@ -67,7 +67,7 @@ def setUp(self):
tagList=self.tagList1,
favorited=self.favorited1,
favoritesCount=self.favoritesCount1,
author=User.objects.get(
author=Profile.objects.get(
username=self.author1))

# Two objects added to db
Expand Down
Loading

0 comments on commit fc95675

Please sign in to comment.