class ArticleListCreateAPIView(ListCreateAPIView):
"""
View that returns articles list based on different article_source & handles
the creation of articles & returns data back.
"""
serializer_class = ArticleSerializer
permission_classes = [IsAuthenticatedOrReadOnly, HasSubscription, NotABlockedUser]
pagination_class = ArticlePageNumberPagination
filter_backends = [SearchFilter, OrderingFilter]
search_fields = ['title']
def get_queryset(self, *args, **kwargs):
article_source = self.request.GET.get('article_source', '')
if article_source == ARTICLE_SOURCES['for_today']:
queryset_list = Article.objects.get_popular_for_today()
elif article_source == ARTICLE_SOURCES['for_week']:
queryset_list = Article.objects.get_popular_of_week()
elif article_source == ARTICLE_SOURCES['for_month']:
queryset_list = Article.objects.get_popular_of_month()
elif article_source == ARTICLE_SOURCES['for_year']:
queryset_list = Article.objects.get_popular_of_year()
elif article_source == ARTICLE_SOURCES['for_all_time']:
queryset_list = Article.objects.get_popular_of_all_time()
elif article_source == ARTICLE_SOURCES['recent']:
queryset_list = Article.objects.get_most_recent()
elif article_source == ARTICLE_SOURCES['drafts']:
queryset_list = Article.objects.get_drafts_by_user(author=self.request.user)
elif article_source == ARTICLE_SOURCES['user']:
username = self.request.GET.get('username', '')
user = User.objects.get(username=username)
queryset_list = Article.objects.get_by_user(author=user)
elif article_source == ARTICLE_SOURCES['favorites']:
username = self.request.GET.get('username', '')
user = User.objects.get(username=username)
c = ContentType.objects.get(app_label="articles", model="article")
# filters activities for given parameters & returns a `QuerySet` of id's of `articles`.
article_ids = Activity.objects.filter(content_type=c, activity_type=Activity.FAVORITE, user=user).values_list('articles', flat=True)
articles = []
for id in article_ids:
article = Article.objects.get(id=id)
articles.append(article)
queryset_list = articles
elif article_source == ARTICLE_SOURCES['subsite']:
subsite_slug = self.request.GET.get('subsite_slug', '')
subsite = Subsite.objects.get(slug=subsite_slug)
queryset_list = subsite.submitted_articles.all()
else:
queryset_list = Article.objects.get_published()
return queryset_list
def perform_create(self, serializer):
content = self.request.data.get("content")
content_json = json.dumps(content)
subsite_id = self.request.data.get("subsite")
subsite = Subsite.objects.get(id=subsite_id)
serializer.save(author=self.request.user, content=content_json, subsite=subsite)
class ArticleRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
"""
View that retrieve, update or delete (if user is the author of) the article.
"""
queryset = Article.objects.get_published()
serializer_class = ArticleSerializer
permission_classes = [IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly]
lookup_field = 'slug'
lookup_url_kwarg = 'slug'
def get_object(self):
obj = get_object_or_404(Article, slug=self.kwargs['slug'])
if not obj.status == Article.PUBLISHED:
if obj.author == self.request.user:
return obj
else:
return None
return obj
def perform_update(self, serializer):
content = self.request.data.get("content")
content_json = json.dumps(content)
serializer.save(author=self.request.user, content=content_json)
class PopularTagsList(APIView):
def get(self, request, format=None):
"""Return a list of popular tags."""
########################################################################
# popular_tags = Article.objects.get_popular_tags()
# popular_tags_list = [
# {'name': popular_tag} for popular_tag in popular_tags
# ]
# return Response(popular_tags_list)
########################################################################
# Needs update as hashtags do not work like that.
subsites = Subsite.objects.get_active()
tags_list = list()
time_boundary = timezone.now() - timezone.timedelta(hours=24)
for subsite in subsites:
total_subsmitted_articles = subsite.submitted_articles.filter(created_at__gt=time_boundary).count()
tags_list.append(
{
'name': subsite.name,
'slug': subsite.slug,
'score': total_subsmitted_articles
}
)
popular_tags = sorted(tags_list, key=lambda subsite: subsite["score"], reverse=True)[:10]
return Response(popular_tags)
class ThreeDaysPopularArticles(ListAPIView):
serializer_class = ShortArticleSerializer
queryset = Article.objects.get_popular_for_three_days()
class MostDiscussedArticles(ListAPIView):
serializer_class = ShortArticleSerializer
queryset = Article.objects.get_most_discussed_for_day()
class LatestArticleId(APIView):
def get(self, request, format=None):
article = Article.objects.all().first()
return Response({'id': article.id})
class ArticleSerializer(serializers.ModelSerializer):
"""
Serializer that represents an article.
"""
author = UserShortDetailSerializer(read_only=True)
subsite = SubsiteShortDetailSerializer(read_only=True)
slug = serializers.SlugField(read_only=True)
total_votes = serializers.IntegerField(read_only=True)
total_favorites = serializers.IntegerField(read_only=True)
total_comments = serializers.IntegerField(read_only=True)
created_at = serializers.DateTimeField(read_only=True)
created_at_naturaltime = serializers.SerializerMethodField()
is_author = serializers.SerializerMethodField()
total_views = serializers.SerializerMethodField()
has_upvoted = serializers.SerializerMethodField()
has_downvoted = serializers.SerializerMethodField()
has_favorited = serializers.SerializerMethodField()
class Meta:
model = Article
fields = [
'id', 'title', 'slug', 'content', 'author', 'is_author',
'total_votes', 'total_comments', 'total_favorites', 'status',
'created_at', 'created_at_naturaltime', 'total_views',
'has_upvoted', 'has_downvoted', 'has_favorited', 'subsite'
]
def get_total_views(self, obj):
hit_count = HitCount.objects.get_for_object(obj)
return hit_count.hits
def get_created_at_naturaltime(self, obj):
return naturaltime(obj.created_at)
def get_is_author(self, obj):
user = None
request = self.context.get('request')
if request and hasattr(request, 'user'):
user = request.user
if user.is_authenticated:
return user == obj.author
return False
def get_has_upvoted(self, obj):
user = None
request = self.context.get('request')
if request and hasattr(request, 'user'):
user = request.user
if user.is_authenticated:
return Activity.handle_activity_status(obj, {"activity_type": Activity.UP_VOTE, "user": user})
return False
def get_has_downvoted(self, obj):
user = None
request = self.context.get('request')
if request and hasattr(request, 'user'):
user = request.user
if user.is_authenticated:
return Activity.handle_activity_status(obj, {"activity_type": Activity.DOWN_VOTE, "user": user})
return False
def get_has_favorited(self, obj):
user = None
request = self.context.get('request')
if request and hasattr(request, 'user'):
user = request.user
if user.is_authenticated:
return Activity.handle_activity_status(obj, {"activity_type": Activity.FAVORITE, "user": user})
return False
class ShortArticleSerializer(serializers.ModelSerializer):
"""
Serializer that represents an short article.
"""
slug = serializers.SlugField(read_only=True)
total_comments = serializers.IntegerField(read_only=True)
content_img = serializers.SerializerMethodField()
class Meta:
model = Article
fields = [
'id', 'title', 'slug', 'content_img', 'total_comments'
]
def get_content_img(self, obj):
request = self.context.get('request')
content_img = "http://127.0.0.1:8000/s/img/default_content_image.jpg"
content_blocks = json.loads(obj.content).get("data")
for cb in content_blocks:
if cb.get("type") == "image":
content_img = request.build_absolute_uri(cb.get("data").get("file").get("url"))
break
return content_img
В данный момент в таблице в бд content = null
Вот так отправляю форму