Skip to content

Commit

Permalink
Git_commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nishalk01 committed Dec 1, 2020
0 parents commit 1264ec0
Show file tree
Hide file tree
Showing 58 changed files with 664 additions and 0 deletions.
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
13 changes: 13 additions & 0 deletions blog_backend/article/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.contrib import admin

# Register your models here.
from django_summernote.admin import SummernoteModelAdmin
from .models import Posts,Comments,UserSession

# Apply summernote to all TextField in model.
class SomeModelAdmin(SummernoteModelAdmin): # instead of ModelAdmin
summernote_fields = ('article_content',)

admin.site.register(Posts, SomeModelAdmin)
admin.site.register(Comments)
admin.site.register(UserSession)
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
24 changes: 24 additions & 0 deletions blog_backend/article/api/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from rest_framework import serializers

from article.models import Posts
from article.models import Comments

class PostSerializer(serializers.ModelSerializer):
class Meta:
model=Posts
fields=['article_name','image','slug','id','article_detail']

class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model=Posts
fields=['article_name','article_content','time_published']

class CommentSerializer(serializers.ModelSerializer):
class Meta:
model=Comments
fields=['commentor_name','comment','comment_on']

class PostCommentSerializer(serializers.ModelSerializer):
class Meta:
model=Comments
fields=['commentor_name','unique_ID','comment','commented_post']
13 changes: 13 additions & 0 deletions blog_backend/article/api/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.urls import path
from .views import api_post,api_get_article,api_get_comment,api_post_comment,api_like_post,api_check_like,SearchArticle
app_name="article"

urlpatterns=[
path("posts/",api_post,name="posts"),
path("article/<slug:slug>/",api_get_article,name="article_content"),
path("comments/<slug:slug>/",api_get_comment,name="article_comment"),
path("comments_post/<slug:slug>/",api_post_comment,name="article_post_comment"),
path("like/<slug:slug>/",api_like_post,name="article_like"),
path("check_like/<slug:slug>/",api_check_like,name="check_like"),
path("article_search/",SearchArticle.as_view(),name="article_search"),
]
156 changes: 156 additions & 0 deletions blog_backend/article/api/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
from rest_framework.decorators import api_view
from django.contrib.auth.models import User
import uuid
import json
from django.db.models import F
from rest_framework.response import Response
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status,generics
from django.shortcuts import get_object_or_404
from rest_framework.filters import SearchFilter,OrderingFilter
from rest_framework.permissions import AllowAny
from .serializers import PostSerializer,ArticleSerializer,CommentSerializer,PostCommentSerializer
from article.models import Posts,Comments,UserSession


def check_for_id(request):
if(request.method=="GET"):
id_request=request.GET["ID"]

elif(request.method=="POST"):
data_id=request.data #handle if there is no id in request *
id_request=data_id["ID"]

if(id_request):
unique_id="" #already present
check=True
else:
unique_id=uuid.uuid4() #create new id
UserSession.objects.create(unique_id=str(unique_id))
check=False
return unique_id,check


@api_view(['GET',])
def api_post(request):
if request.method == "GET":
posts=Posts.objects.all()
serializer=PostSerializer(posts,context={"request":request},many=True)
data_to=json.loads(json.dumps(serializer.data))
unique_id,check=check_for_id(request) #handle request without id dict *
print(check)
data_to={"data":data_to,"unique_id":unique_id}
return Response(data_to)

@api_view(['GET',])
def api_get_article(request,slug):
if request.method=="GET":
try:
get_article=Posts.objects.get(slug=slug)
get_article.views =get_article.views+1
get_article.save()
# print(get_article.views)
serializer=ArticleSerializer(get_article)
return Response(serializer.data)
except:
return Response(status=status.HTTP_404_NOT_FOUND)


@api_view(['GET',])
def api_get_comment(request,slug):
if request.method=="GET":
get_comments=Comments.objects.filter(commented_post__slug__contains=slug)
unique_id=request.GET["ID"]
unique_id_from_check,_=check_for_id(request)
print(unique_id_from_check)
if(unique_id):
instance_user=UserSession.objects.get(unique_id=str(unique_id))
obj=Comments.objects.all().filter(unique_ID=instance_user.id)


serializer=CommentSerializer(get_comments,many=True)
comment_data=json.loads(json.dumps(serializer.data))
try:
commentor_name=obj[0].commentor_name
except (IndexError,UnboundLocalError):
commentor_name=""
comment_get={"comment_data":comment_data,"commentor_name":commentor_name,"unique_id_get_comment":unique_id_from_check}
return Response(comment_get)



@api_view(['POST'])
def api_post_comment(request,slug):
if request.method=="POST":
comment_data=request.data
comment_data["commented_post"]=str(slug)
comment_data_json=json.dumps(comment_data)
print(comment_data["commentor_name"])
try:
commentor_name=comment_data["commentor_name"]
# commented_post=comment_data["commented_post"]
ID=comment_data["ID"]
comment=comment_data["comment"]

instance_post=Posts.objects.get(slug=slug)
instance_ID=UserSession.objects.get(unique_id=ID)
# print(instance_ID.id)
Comments.objects.create(commentor_name=commentor_name,commented_post=instance_post,unique_ID=instance_ID,comment=comment)
return Response({'message': 'comment uploaded'},status=status.HTTP_201_CREATED)
except:
return Response({'message': 'comment not proper'},status=status.HTTP_400_BAD_REQUEST)

# {
# "user_name":"nishal",
# "ID":"uud",
# "commented_post":"how are you"
# "comment":"comment it is",
# }


@api_view(['POST',])
def api_like_post(request,slug):
if request.method=="POST":
unique_id,check=check_for_id(request)
print(request.data["ID"])
unique_id_for_userauth=request.data["ID"]
unique_id_instance=UserSession.objects.get(unique_id=unique_id_for_userauth)#handle query doesnot exists*
post_instance=Posts.objects.get(slug=slug)#handle slug not there*
if(post_instance.likes.filter(id=unique_id_instance.id)):
post_instance.likes.remove(unique_id_instance)
like_status=False
else:
post_instance.likes.add(unique_id_instance)
like_status=True
like_status_obj={"like_status":like_status}
return Response(like_status_obj,status.HTTP_200_OK)

@api_view(['GET',])
def api_check_like(request,slug):#change this method later*
if request.method=="GET":
check_like={"check_like":False}
if(request.GET["ID"]):
post_instance=Posts.objects.get(slug=slug)
unique_id,check=check_for_id(request)
check_like["unique_id"]=unique_id
unique_id_for_check=request.GET["ID"]
print(check_like)
unique_id_check_instance=UserSession.objects.get(unique_id=unique_id_for_check)
print(post_instance)
if(post_instance.likes.filter(id=unique_id_check_instance.id)):
check_like["check_like"]=True
return Response(check_like,status.HTTP_200_OK)
else:
return Response(check_like,status.HTTP_200_OK)
else:
return Response(check_like,status.HTTP_200_OK)

class SearchArticle(generics.ListAPIView):
queryset=Posts.objects.all()
serializer_class=PostSerializer
filter_backends= (SearchFilter, OrderingFilter)
search_fields=['article_name','article_detail']


# https://www.nishalk01.pythonanywhere.com/
5 changes: 5 additions & 0 deletions blog_backend/article/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class ArticleConfig(AppConfig):
name = 'article'
47 changes: 47 additions & 0 deletions blog_backend/article/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Generated by Django 3.1.3 on 2020-12-01 15:28

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='UserSession',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('unique_id', models.CharField(max_length=150)),
],
),
migrations.CreateModel(
name='Posts',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(upload_to='')),
('article_detail', models.TextField(max_length=200)),
('article_name', models.CharField(max_length=150)),
('article_content', models.TextField()),
('slug', models.SlugField(unique=True)),
('time_published', models.DateField(auto_now=True)),
('views', models.IntegerField(default=0, null=True)),
('likes', models.ManyToManyField(blank=True, related_name='likes', to='article.UserSession')),
],
),
migrations.CreateModel(
name='Comments',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('commentor_name', models.CharField(max_length=100, null=True)),
('comment', models.TextField()),
('comment_on', models.DateTimeField(auto_now_add=True)),
('commented_post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='article.posts')),
('unique_ID', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='ID', to='article.usersession')),
],
),
]
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
50 changes: 50 additions & 0 deletions blog_backend/article/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify


class UserSession(models.Model):
unique_id=models.CharField(max_length=150)
#probably need name field

def __str__(self):
return str(self.unique_id)

class Posts(models.Model):
image=models.ImageField()#for post card
article_detail=models.TextField(max_length=200)
article_name=models.CharField(max_length=150)#both for post_card and article page
article_content=models.TextField()#for article page
slug = models.SlugField(null=False, unique=True)#both
time_published=models.DateField(auto_now=True)#article_page
views=models.IntegerField(default=0,null=True)

likes=models.ManyToManyField(UserSession,blank=True, related_name='likes')#for article_page
# desc=models.TextField()

def __str__(self):
return str(self.article_name)

def total_likes(self):
return self.likes.count()

def save(self, *args, **kwargs):
self.slug = slugify(f"{self.article_name} {self.time_published}")
super(Posts, self).save(*args, **kwargs)




class Comments(models.Model):
commentor_name=models.CharField(max_length=100,null=True)
commented_post=models.ForeignKey(Posts,on_delete=models.CASCADE)
unique_ID=models.ForeignKey(UserSession,on_delete=models.CASCADE,null=True,related_name="ID")
comment=models.TextField()
comment_on=models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.commentor_name)





3 changes: 3 additions & 0 deletions blog_backend/article/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
3 changes: 3 additions & 0 deletions blog_backend/article/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.shortcuts import render

# Create your views here.
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
16 changes: 16 additions & 0 deletions blog_backend/blog_backend/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for blog_backend 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/3.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

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

application = get_asgi_application()
Loading

0 comments on commit 1264ec0

Please sign in to comment.