Skip to content

Commit

Permalink
message model
Browse files Browse the repository at this point in the history
  • Loading branch information
walosha committed Jan 21, 2023
1 parent d1004c1 commit 0b87906
Show file tree
Hide file tree
Showing 18 changed files with 205 additions and 62 deletions.
1 change: 1 addition & 0 deletions core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"event",
"blog",
"poll",
"message"

]
# AUTH_USER_MODEL = "users.CustomUser"
Expand Down
3 changes: 2 additions & 1 deletion core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
path('api/auth/', include('account.urls')),
path('api/polls/', include('poll.urls')),
path('api/attendances/', include('attendance.urls')),
path('api/messages/', include('message.urls')),
path('api/events/', include('event.urls')),
path('api/', include('blog.urls')),
path('api/blogs/', include('blog.urls')),
# Optional UI:
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
path('api/doc/',
Expand Down
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion pledge/apps.py → message/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@

class PledgeConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'pledge'
name = 'message'
2 changes: 2 additions & 0 deletions message/enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
QUESTION_TYPES = (("PRAYER_REQUEST", "PRAYER_REQUEST"), ("COUNSELLING", "COUNSELLING"),
("OTHERS", "OTHERS"), ("WHISTLEBLOWING", "WHISTLEBLOWING"), ("SUGGESTION", "SUGGESTION"))
33 changes: 33 additions & 0 deletions message/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Generated by Django 4.0.8 on 2023-01-21 09:14

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Message',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('title', models.CharField(max_length=100)),
('body', models.TextField(blank=True)),
('message_type', models.CharField(choices=[], max_length=20)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='message', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-created_at',),
},
),
]
18 changes: 18 additions & 0 deletions message/migrations/0002_alter_message_message_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.0.8 on 2023-01-21 09:21

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('message', '0001_initial'),
]

operations = [
migrations.AlterField(
model_name='message',
name='message_type',
field=models.CharField(choices=[('PRAYER_REQUEST', 'PRAYER_REQUEST'), ('COUNSELLING', 'COUNSELLING'), ('OTHERS', 'OTHERS'), ('WHISTLEBLOWING', 'WHISTLEBLOWING'), ('SUGGESTION', 'SUGGESTION')], max_length=20),
),
]
File renamed without changes.
19 changes: 19 additions & 0 deletions message/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from django.db import models
from core.models import AuditableModel
from account.models import CustomUser
from .enums import QUESTION_TYPES
# Create your models here.


class Message (AuditableModel):
title = models.CharField(max_length=100, blank=False)
user = models.ForeignKey(
CustomUser, on_delete=models.CASCADE, related_name='message')
body = models.TextField(blank=True)
message_type = models.CharField(max_length=20, choices=QUESTION_TYPES)

class Meta:
ordering = ('-created_at',)

def __str__(self) -> str:
return self.title
15 changes: 15 additions & 0 deletions message/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# django #selenium #webscraping
from rest_framework import serializers
from django.contrib.auth.models import User, Group
from .models import Message


class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
# fields = ('id', 'title', 'description', 'completed')
# Shortcut for getting all fields
fields = '__all__'
extra_kwargs = {
'user': {'read_only': True},
}
File renamed without changes.
13 changes: 13 additions & 0 deletions message/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from .views import MessageListCreateAPIView, MessageRetrieveAPIView, MessageUpdateAPIView, MessageDestroyAPIView

urlpatterns = [
path('<uuid:pk>/', MessageRetrieveAPIView.as_view(),
name="message_detail"),
path('<uuid:pk>/', MessageUpdateAPIView.as_view(),
name="message_update"),
path('<uuid:pk>/', MessageDestroyAPIView.as_view(),
name="message_delete"),
path('', MessageListCreateAPIView.as_view(), name="message_list")
]
27 changes: 27 additions & 0 deletions message/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from .models import Message
from .serializers import MessageSerializer
from rest_framework import generics


class MessageListCreateAPIView(generics.ListCreateAPIView):
queryset = Message.objects.all()
serializer_class = MessageSerializer

def perform_create(self, serializer):
print(self, "----------", serializer)
serializer.save(user=self.request.user)


class MessageRetrieveAPIView(generics.RetrieveAPIView):
queryset = Message.objects.all()
serializer_class = MessageSerializer


class MessageUpdateAPIView(generics.UpdateAPIView):
queryset = Message.objects.all()
serializer_class = MessageSerializer


class MessageDestroyAPIView(generics.DestroyAPIView):
queryset = Message.objects.all()
serializer_class = MessageSerializer
3 changes: 0 additions & 3 deletions pledge/models.py

This file was deleted.

3 changes: 0 additions & 3 deletions pledge/views.py

This file was deleted.

122 changes: 70 additions & 52 deletions poll/serialisers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from rest_framework import serializers
from .models import Poll, PollQuestion, PollCategory
from .models import Poll, PollQuestion, PollCategory, PollQuestionOption


class PollCategorySerializer(serializers.ModelSerializer):
Expand All @@ -24,10 +24,33 @@ def to_representation(self, instance):
return data


class QuestionOptionSerializer(serializers.ModelSerializer):
class Meta:
model = PollQuestionOption
fields = '__all__'
extra_kwargs = {
'question': {'read_only': True}
}


class QuestionSerializer(serializers.ModelSerializer):
options = QuestionOptionSerializer(many=True, write_only=True)

class Meta:
model = PollQuestion
fields = '__all__'
extra_kwargs = {
'position': {'read_only': True},
'poll': {'read_only': True},
}

def to_representation(self, instance):
option = instance.question_option.all()
data = super().to_representation(instance)
data['options'] = QuestionOptionSerializer(
option, many=True).data if option else None
data['poll_instruction'] = instance.poll.poll_instruction
return data


class PollListSerializer(serializers.ModelSerializer):
Expand All @@ -46,58 +69,53 @@ class QuestionCreateSerializer(serializers.Serializer):
questions = serializers.ListSerializer(
child=QuestionSerializer(), required=True)

# def validate(self, attrs):
# questions = attrs['questions']
# poll = self.context['poll']
# poll_type = poll.type
# question_type = []
# special_polls = ['CANDIDATE_POPULARITY', 'PARTY_POPULARITY',
# 'NEEDS_ASSESSMENT'] # analytical polls

# qs = Question.objects.filter(poll=poll)
# poll_questions = qs.exclude(poll=poll) if self.instance else qs
# if poll_questions.exists():
# raise serializers.ValidationError(
# {'questions': 'questions already set up for this poll'})
# if poll_type in special_polls:
# for question in questions:
# if question['type'] in special_polls:
# question_type.append(question['type'])
# if poll.type not in question_type:
# raise serializers.ValidationError(
# {'type': f'must contain a {poll_type} type'})
# elif len(question_type) > 1:
# raise serializers.ValidationError(
# {'type': f'invalid questions'}) # todo improve error message
# return attrs

# def to_representation(self, instance):
# return QuestionSerializer(instance).data

# def create(self, validated_data):
# optional_options = [
# {'value': 'Others', 'key': 'default'},
# {'value': 'Undecided', 'key': 'default'},
# {'value': 'Prefer not to say', 'key': 'default'}
# ]
# poll = self.context['poll']
# questions = validated_data['questions']
# poll_instruction = validated_data['poll_instruction']
# for question in questions:
# options = question.pop('options')
# if question['type'] == poll.type:
# question['required'] = True
# question_obj = Question.objects.create(**question, poll=poll)
# for option in options:
# QuestionOption.objects.create(**option, question=question_obj)
# if question['type'] in ['CANDIDATE_POPULARITY', 'PARTY_POPULARITY']:
# for optional_option in optional_options:
# QuestionOption.objects.create(
# **optional_option, question=question_obj)
def validate(self, attrs):
# questions = attrs['questions']
# poll = self.context['poll']
# poll_type = poll.type
# question_type = []
# special_polls = ['CANDIDATE_POPULARITY', 'PARTY_POPULARITY',
# 'NEEDS_ASSESSMENT'] # analytical polls

# qs = Question.objects.filter(poll=poll)
# poll_questions = qs.exclude(poll=poll) if self.instance else qs
# if poll_questions.exists():
# raise serializers.ValidationError(
# {'questions': 'questions already set up for this poll'})
# if poll_type in special_polls:
# for question in questions:
# if question['type'] in special_polls:
# question_type.append(question['type'])
# if poll.type not in question_type:
# raise serializers.ValidationError(
# {'type': f'must contain a {poll_type} type'})
# elif len(question_type) > 1:
# raise serializers.ValidationError(
# {'type': f'invalid questions'}) # todo improve error message
return attrs

# poll.poll_instruction = poll_instruction
# poll.save()
# return True
def to_representation(self, instance):
return QuestionSerializer(instance).data

def create(self, validated_data):

poll = self.context['poll']
questions = validated_data['questions']
poll_instruction = validated_data['poll_instruction']
for question in questions:
options = question.pop('options')
if question['type'] == poll.type:
question['required'] = True
question_obj = PollQuestion.objects.create(
**question, poll=poll)
for option in options:
PollQuestionOption.objects.create(
**option, question=question_obj)

poll.poll_instruction = poll_instruction
print("===========", poll)
poll.save()
return True

# def update(self, instance, validated_data):
# """
Expand Down
6 changes: 4 additions & 2 deletions poll/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.response import Response
from .serialisers import PollCategorySerializer, PollSerializer, PollListSerializer, QuestionCreateSerializer
from .serialisers import PollCategorySerializer, PollSerializer, PollListSerializer, QuestionCreateSerializer, QuestionSerializer
from .models import Poll, PollQuestion, PollCategory
from .filters import PollFilter
from account.permissions import IsAdmin
Expand Down Expand Up @@ -60,7 +60,9 @@ def list_create_update_questions(self, request, pk=None):
poll = self.get_object()
if request.method == 'GET':
qs = PollQuestion.objects.filter(poll=poll)
serializer = PollQuestion(qs, many=True)
print('qs', qs)
serializer = QuestionSerializer(qs, many=True)
print({"serializer": serializer})
return Response(
{'success': True, 'data': serializer.data},
status=status.HTTP_200_OK)
Expand Down

0 comments on commit 0b87906

Please sign in to comment.