Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Frontend #93

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion backend/api/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from django.contrib import admin

# Register your models here.
from backend.api.models import Message
class MessageAdmin(admin.ModelAdmin):
list_display=('user','title','text')

admin.site.register(Message, MessageAdmin)
1 change: 0 additions & 1 deletion backend/api/apps.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from django.apps import AppConfig


class AppConfig(AppConfig):
name = 'api'
47 changes: 47 additions & 0 deletions backend/api/migrations/0002_auto_20220205_1154.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Generated by Django 2.1.4 on 2022-02-05 11:54

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0001_initial'),
]

operations = [
migrations.RemoveField(
model_name='message',
name='body',
),
migrations.RemoveField(
model_name='message',
name='subject',
),
migrations.AddField(
model_name='message',
name='text',
field=models.TextField(blank=True, null=True),
),
migrations.AddField(
model_name='message',
name='timestamp',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='message',
name='title',
field=models.CharField(blank=True, max_length=200, null=True),
),
migrations.AddField(
model_name='message',
name='user',
field=models.ForeignKey(default=123, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]
25 changes: 17 additions & 8 deletions backend/api/models.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
from __future__ import unicode_literals
from datetime import datetime
from django.conf import settings
from django.db import models
from rest_framework import serializers


class Message(models.Model):
subject = models.CharField(max_length=200)
body = models.TextField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200, null=True, blank=True)
text = models.TextField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)

def __str__(self):
return str(self.user.username)

@property
def owner(self):
return self.user

class MessageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Message
fields = ('url', 'subject', 'body', 'pk')
# class MessageSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = Message
# fields = ('url', 'subject', 'body', 'pk')
Empty file added backend/api/post/__init__.py
Empty file.
8 changes: 8 additions & 0 deletions backend/api/post/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self,request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True

return obj.owner == request.user
18 changes: 18 additions & 0 deletions backend/api/post/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from backend.api.models import Message
from rest_framework import serializers

class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Message
fields = (
'pk', 'user', 'title', 'text', 'timestamp'
)
read_only_fields = ['user']

def validate_title(self, value):
qs = Message.objects.filter(title__iexact=value)
if self.instance:
qs = qs.exclude(pk=self.exclude.pk)
if(qs.exists()):
return serializers.ValidationError("This is already created.")
return value
7 changes: 7 additions & 0 deletions backend/api/post/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.conf.urls import url
from .views import PostAPIView, PostRudView

urlpatterns = [
url(r'^$', PostAPIView.as_view(), name='post-api'),
url(r'^(?P<pk>\d+)/$', PostRudView.as_view(), name='post-rud'),
]
29 changes: 29 additions & 0 deletions backend/api/post/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from django.db.models import Q
from backend.api.post.permissions import IsOwnerOrReadOnly
from backend.api.post.serializers import PostSerializer
from rest_framework import generics,mixins
from backend.api.models import Message
from .serializers import PostSerializer

class PostAPIView(mixins.CreateModelMixin, generics.ListAPIView):
lookup_field = 'pk'
serializer_class = PostSerializer

def get_queryset(self):
qs = Message.objects.all()
query = self.request.GET.get('q')
if query is not None:
qs = qs.filter(Q(title__icontains=query)|Q(text__icontains=query)).distinct()
return qs
def perform_create(self, serialzer):
serialzer.save(user=self.request.user)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)

class PostRudView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'pk'
serializer_class = PostSerializer
permission_classes = [IsOwnerOrReadOnly]

def get_queryset(self):
return Message.objects.all()
5 changes: 3 additions & 2 deletions backend/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from django.views.decorators.cache import never_cache
from rest_framework import viewsets

from .models import Message, MessageSerializer
from backend.api.post.serializers import PostSerializer
from .models import Message


# Serve Vue Application
Expand All @@ -14,6 +15,6 @@ class MessageViewSet(viewsets.ModelViewSet):
API endpoint that allows messages to be viewed or edited.
"""
queryset = Message.objects.all()
serializer_class = MessageSerializer
serializer_class = PostSerializer


11 changes: 11 additions & 0 deletions backend/settings/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,14 @@
# Insert Whitenoise Middleware at top but below Security Middleware
# MIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware',)
# http://whitenoise.evans.io/en/stable/django.html#make-sure-staticfiles-is-configured-correctly

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
20 changes: 10 additions & 10 deletions backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,26 @@
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
"""

# from os import name
from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path, include
# from django.urls import path
from rest_framework import routers

from .api.views import index_view, MessageViewSet
from .api.post.views import PostAPIView, PostRudView
# from .api.views import index_view, MessageViewSet

router = routers.DefaultRouter()
router.register('messages', MessageViewSet)
router.register('post', PostAPIView.as_view(),'post')

urlpatterns = [

# http://localhost:8000/
path('', index_view, name='index'),
# path('', index_view, name='index'),

# http://localhost:8000/api/<router-viewsets>
path('api/', include(router.urls)),
# path('api/', include(router.urls)),

# http://localhost:8000/api/admin/
path('api/admin/', admin.site.urls),
url(r'^admin/', admin.site.urls),
url(r'^api/post/', include('backend.api.post.urls')),
]


9 changes: 8 additions & 1 deletion manage.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

if __name__ == '__main__':

def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings.dev')
try:
from django.core.management import execute_from_command_line
Expand All @@ -13,3 +16,7 @@
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Loading