- Clean Up API Urls and Views:
- from rest_framework.authentication import SessionAuthentication
- from rest_framework.decorators import api_view, permission_classes, authentication_classes
- from rest_framework.permissions import IsAuthenticated
- from rest_framework.response import Response
- from .models import Tweet
- from .forms import TweetForm
- from .serializers import (
- TweetSerializer,
- TweetActionSerializer,
- TweetCreateSerializer
- )
- def local_tweets_list_view(request, args, *kwargs):
- def local_tweets_detail_view(request, tweet_id, args, *kwargs):
- def local_tweets_profile_view(request, username, args, *kwargs):
- removed other parts
Clean Up API Urls and Views:
This part is to use “api” directory to organize urls and views.
- create directory /tweets/api
- create /tweets/api/init.py (no actual content)
- create /tweets/api/urls.py
- create /tweets/api/views.py
- copy content in /tweets/urls.py and paste into /tweets/api/urls.py
- modify the content to fit ```python from django.contrib import admin from django.urls import path
from .views import (
# home_view,tweet_detail_view,tweet_list_view,tweet_create_view,tweet_delete_view,tweet_action_view,
)
urlpatterns = [
path(‘’, tweet_list_view),
path(‘action/‘, tweet_action_view),
path(‘create/‘, tweet_create_view),
path(‘
- also copy, paste and modify /tweets/views.py into create /tweets/api/views.py```pythonimport randomfrom django.http import HttpResponse, JsonResponse, HttpResponseRedirectfrom django.shortcuts import render, redirectfrom django.utils.http import is_safe_urlfrom django.conf import settingsfrom rest_framework.authentication import SessionAuthenticationfrom rest_framework.decorators import api_view, permission_classes, authentication_classesfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.response import Response# from .models import Tweet# from .forms import TweetForm# from .serializers import (# TweetSerializer,# TweetActionSerializer,# TweetCreateSerializer# )from ..models import Tweetfrom ..forms import TweetFormfrom ..serializers import (TweetSerializer,TweetActionSerializer,TweetCreateSerializer)ALLOWED_HOSTS = settings.ALLOWED_HOSTS# def home_view(request, *args, **kwargs):# username = None# if request.user.is_authenticated:# username = request.user.username# return render(request, "pages/home.html", context={"username": username}, status=200)# def local_tweets_list_view(request, *args, **kwargs):# return render(request, "tweets/list.html")# def local_tweets_detail_view(request, tweet_id, *args, **kwargs):# return render(request, "tweets/detail.html", context={"tweet_id": tweet_id})# def local_tweets_profile_view(request, username, *args, **kwargs):# return render(request, "tweets/profile.html", context={"profile_username": username})@api_view(['POST']) # http method the client === POST# @authentication_classes([SessionAuthentication])@permission_classes([IsAuthenticated])def tweet_create_view(request, *args, **kwargs):print(request.user)serializer = TweetCreateSerializer(data=request.data)if serializer.is_valid(raise_exception=True): # send back what the error isserializer.save(user=request.user)return Response(serializer.data, status=201)return Response({}, status=400)def tweet_create_view_pure_django(request, *args, **kwargs):user = request.userif not request.user.is_authenticated:user = Noneif request.is_ajax():return JsonResponse({}, status=401)return redirect(settings.LOGIN_URL)form = TweetForm(request.POST or None)print('post data is', request.POST)next_url = request.POST.get("next") or Noneif form.is_valid():obj = form.save(commit=False)obj.user = request.userobj.save()if request.is_ajax():return JsonResponse(obj.serialize(), status=201)if next_url != None and is_safe_url(next_url, ALLOWED_HOSTS):return redirect(next_url)form = TweetForm()if form.errors:if request.is_ajax():return JsonResponse(form.errors, status=400)return render(request, 'components/form.html', context={"form": form})@api_view(['GET']) # http method the client === POSTdef tweet_list_view(request, *args, **kwargs):qs = Tweet.objects.all() # grab all objects in Tweetusername = request.GET.get('username') # ?username=rootif username != None:# filter that username w/o case sensitiveqs = qs.filter(user__username__iexact=username)serializer = TweetSerializer(qs, many=True)return Response(serializer.data)def tweet_list_view_pure_django(request, *args, **kwargs):qs = Tweet.objects.all() # grab all objects in Tweet# tweets_list = [{"id" : x.id, "content" : x.content, "likes" : random.randint(0, 1000)} for x in qs]tweets_list = [x.serialize() for x in qs]data = {"isUser": False,"response": tweets_list}return JsonResponse(data)@api_view(['GET']) # http method the client === GETdef tweet_detail_view(request, tweet_id, *args, **kwargs):qs = Tweet.objects.filter(id=tweet_id)if not qs.exists():return Response({}, status=404)obj = qs.first()serializer = TweetSerializer(obj)return Response(serializer.data, status=200)def tweet_detail_view_pure_django(request, tweet_id, *args, **kwargs):data = {"id": tweet_id,}status = 200try:obj = Tweet.objects.get(id=tweet_id)data['content'] = obj.contentexcept:data['message'] = "Not found"status = 404return JsonResponse(data, status=status)@api_view(['DELETE', 'POST'])@permission_classes([IsAuthenticated])def tweet_delete_view(request, tweet_id, *args, **kwargs):qs = Tweet.objects.filter(id=tweet_id)if not qs.exists():return Response({}, status=404)qs = qs.filter(user=request.user)if not qs.exists():return Response({"message": "You cannot delete this tweet"}, status=401)obj = qs.first()obj.delete()return Response({"Tweet removed"}, status=200)@api_view(['POST'])@permission_classes([IsAuthenticated])def tweet_action_view(request, *args, **kwargs):# id is required# action: like, unlike, retweetserializer = TweetActionSerializer(data=request.data)if serializer.is_valid(raise_exception=True):data = serializer.validated_datatweet_id = data.get("id")action = data.get("action")content = data.get("content")qs = Tweet.objects.filter(id=tweet_id)if not qs.exists():return Response({}, status=404)obj = qs.first()if action == "like":# add the current user into the like listobj.likes.add(request.user)serializer = TweetSerializer(obj)return Response(serializer.data, status=200)elif action == "unlike":# remove the current user from the like listobj.likes.remove(request.user)serializer = TweetSerializer(obj)return Response(serializer.data, status=200)elif action == "retweet":new_tweet = Tweet.objects.create(user=request.user,parent=obj,content=content)serializer = TweetSerializer(new_tweet)# return Response(serializer.data, status=200)return Response(serializer.data, status=201)return Response({}, status=200)
- modify original files
- /tweets/views.py ```python import random from django.http import HttpResponse, JsonResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.utils.http import is_safe_url from django.conf import settings
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .models import Tweet
from .forms import TweetForm
from .serializers import (
TweetSerializer,
TweetActionSerializer,
TweetCreateSerializer
)
ALLOWED_HOSTS = settings.ALLOWED_HOSTS
def home_view(request, args, *kwargs): username = None if request.user.is_authenticated: username = request.user.username return render(request, “pages/home.html”, context={“username”: username}, status=200)
def local_tweets_list_view(request, args, *kwargs):
def tweets_list_view(request, args, *kwargs): return render(request, “tweets/list.html”)
def local_tweets_detail_view(request, tweet_id, args, *kwargs):
def tweets_detail_view(request, tweet_id, args, *kwargs): return render(request, “tweets/detail.html”, context={“tweet_id”: tweet_id})
def local_tweets_profile_view(request, username, args, *kwargs):
def tweets_profile_view(request, username, args, *kwargs): return render(request, “tweets/profile.html”, context={“profile_username”: username})
removed other parts
- change urls links in /Twittme/urls.py```pythonfrom django.contrib import adminfrom django.urls import path, re_path, includefrom django.conf import settingsfrom django.conf.urls.static import staticfrom django.views.generic import TemplateViewfrom tweets.views import (# local_tweets_list_view,# local_tweets_detail_view,# local_tweets_profile_view,tweets_list_view,tweets_detail_view,tweets_profile_view,)urlpatterns = [path('admin/', admin.site.urls),# path('api/tweets/', include('tweets.urls')),path('api/tweets/', include('tweets.api.urls')),# path('', local_tweets_list_view),# path('<int:tweet_id>', local_tweets_detail_view),# path('profile/<str:username>', local_tweets_profile_view),path('', tweets_list_view),path('<int:tweet_id>', tweets_detail_view),path('profile/<str:username>', tweets_profile_view),]if settings.DEBUG:urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
And it has the same feature as the reactjs/django project before, but with a new intergrated api directory.
