Quiz

Форк
0
/
views.py 
210 строк · 8.8 Кб
1
from django.contrib import messages
2
from django.core.cache import cache
3
from django.db.models import Q, Sum
4
from django.http import HttpResponseRedirect
5
from django.shortcuts import render, get_object_or_404
6
from django.urls import reverse, reverse_lazy
7
from django.views.generic import TemplateView, DeleteView, UpdateView, CreateView, DetailView
8

9
from authapp.models import Remark, AuthUser, QuestionRatedByUser
10
from questions.models import Question, Category, Type, SubType, Answer, QuestionComplaint
11

12
from variables import *
13

14

15
class QuestionView(TemplateView):
16
    template_name = 'questions/qes_list.html'
17

18
    def get_context_data(self, **kwargs):
19
        context_data = super().get_context_data(**kwargs)
20
        context_data['object_list'] = Question.objects.all()
21
        context_data['complaints'] = QuestionComplaint.objects.filter()
22
        return context_data
23

24
    def post(self, request, *args, **kwargs):
25
        if all(
26
                (
27
                        request.POST.get('question_id'),
28
                        request.POST.get('complaint'),
29
                )
30
        ):
31
            print(request.POST)
32
            new_complaint = QuestionComplaint.objects.create(
33
                question=Question.objects.get(pk=int(request.POST.get('question_id'))),
34
                text=request.POST.get('complaint')
35
            )
36
            new_complaint.save()
37
            messages.add_message(request, messages.INFO, 'Замечание добавлено')
38
            return HttpResponseRedirect(reverse('quest:quest'))
39
        else:
40
            messages.add_message(
41
                request, messages.WARNING,
42
                'Не удалось добавить замечание'
43
            )
44
            return HttpResponseRedirect(reverse('quest:quest'))
45

46

47
class QuestionDeleteView(DeleteView):
48
    model = Question
49
    success_url = reverse_lazy('quest:quest')
50

51

52
class QuestionUpdateView(UpdateView):
53
    model = Question
54
    fields = ('question', 'is_validated')
55
    success_url = reverse_lazy('quest:quest')
56

57

58
class AddQuestionsView(TemplateView):
59
    template_name = 'questions/add_quest.html'
60

61
    def post(self, request, *args, **kwargs):
62
        try:
63
            if all(
64
                    (
65
                            request.POST.get('question'),
66
                            request.POST.get('category'),
67
                            request.POST.get('type'),
68
                            request.POST.get('subtype'),
69
                            request.POST.get('answer'),
70
                    )
71
            ):
72
                new_category = Category.objects.create(
73
                    name=request.POST.get('category')
74
                )
75
                new_category.save()
76
                new_type = Type.objects.create(
77
                    name=request.POST.get('type')
78
                )
79
                new_type.save()
80
                new_subtype = SubType.objects.create(
81
                    name=request.POST.get('subtype'),
82
                    type=Type.objects.get(name=request.POST.get('type'))
83
                )
84
                new_subtype.save()
85
                new_answer = Answer.objects.create(
86
                    answer=request.POST.get('answer'),
87
                    subtype=SubType.objects.get(name=request.POST.get('subtype'))
88
                )
89
                new_answer.save()
90
                new_quest = Question.objects.create(
91
                    category=Category.objects.get(name=request.POST.get('category')),
92
                    question=request.POST.get('question'),
93
                    answer=Answer.objects.get(answer=request.POST.get('answer')),
94
                )
95
                new_quest.save()
96
                messages.add_message(request, messages.INFO, 'Вопрос добавлен успешно')
97
                return HttpResponseRedirect(reverse('quest:add_quest'))
98
            else:
99
                messages.add_message(
100
                    request, messages.WARNING,
101
                    'Не удалось добавить вопрос'
102
                )
103
                return HttpResponseRedirect(reverse('quest:add_quest'))
104
        except Exception as ex:
105
            messages.add_message(
106
                request, messages.WARNING,
107
                'Не удалось добавить вопрос'
108
            )
109
            return HttpResponseRedirect(reverse('quest:add_quest'))
110

111

112
class GradeQuestionView(TemplateView):
113
    template_name = 'questions/grade_quest.html'
114

115
    def get_context_data(self, **kwargs):
116
        context_data = super().get_context_data(**kwargs)
117
        context_data['question_list'] = Question.objects.filter(~Q(pk__in=[x.question.pk for x in Remark.objects.filter(author=self.request.user)]) &
118
                                                                Q(is_validated=False)).order_by('?').first()
119
        context_data['remark_list'] = Remark.objects.filter(question=context_data['question_list'])
120
        return context_data
121

122
    def post(self, request, *args, **kwargs):
123
        try:
124
            if all(
125
                    (
126
                            request.POST.get('question'),
127
                            request.POST.get('text'),
128
                            request.POST.get('author'),
129
                            request.POST.get('rating')
130
                    )
131
            ):
132
                new_remark = Remark.objects.create(
133
                    question=Question.objects.get(question=request.POST.get('question')),
134
                    text=request.POST.get('text'),
135
                    author=AuthUser.objects.get(username=request.POST.get('author')),
136
                    rating=request.POST.get('rating'),
137
                )
138
                new_remark.save()
139
                question = Question.objects.get(question=request.POST.get('question'))
140
                remark = Remark.objects.filter(question=question).aggregate(Sum('rating'))
141
                if remark['rating__sum'] >= VOTES:
142
                    question.is_validated = True
143
                    question.save()
144
                    question.answer.is_validated = True
145
                    question.answer.save()
146
                elif remark['rating__sum'] <= -VOTES:
147
                    question.delete()
148
                messages.add_message(request, messages.INFO, 'Оценка выполнена')
149
                return HttpResponseRedirect(reverse('quest:grade_quest'))
150
            else:
151
                messages.add_message(
152
                    request, messages.WARNING,
153
                    'Не удалось выполнить оценку'
154
                )
155
                return HttpResponseRedirect(reverse('quest:grade_quest'))
156
        except Exception as ex:
157
            messages.add_message(
158
                request, messages.WARNING,
159
                'Не удалось выполнить оценку'
160
            )
161
            return HttpResponseRedirect(reverse('quest:grade_quest'))
162

163

164
class OfferQuestionView(TemplateView):
165
    template_name = 'questions/offer_quest.html'
166

167
    def get_context_data(self, **kwargs):
168
        context_data = super().get_context_data(**kwargs)
169
        context_data['type_list'] = Type.objects.all()
170
        context_data['subtype_list'] = SubType.objects.all()
171
        context_data['category_list'] = Category.objects.all()
172

173
        return context_data
174

175
    def post(self, request, *args, **kwargs):
176
        try:
177
            if all(
178
                    (
179
                            request.POST.get('question'),
180
                            request.POST.get('category'),
181
                            request.POST.get('type'),
182
                            request.POST.get('subtype'),
183
                            request.POST.get('answer'),
184
                    )
185
            ):
186
                new_answer = Answer.objects.create(
187
                    answer=request.POST.get('answer'),
188
                    subtype=SubType.objects.get(name=request.POST.get('subtype'))
189
                )
190
                new_answer.save()
191
                new_quest = Question.objects.create(
192
                    category=Category.objects.get(name=request.POST.get('category')),
193
                    question=request.POST.get('question'),
194
                    answer=new_answer,
195
                )
196
                new_quest.save()
197
                messages.add_message(request, messages.INFO, 'Вопрос добавлен успешно')
198
                return HttpResponseRedirect(reverse('quest:offer_quest'))
199
            else:
200
                messages.add_message(
201
                    request, messages.WARNING,
202
                    'Не удалось добавить вопрос'
203
                )
204
                return HttpResponseRedirect(reverse('quest:offer_quest'))
205
        except Exception as ex:
206
            messages.add_message(
207
                request, messages.WARNING,
208
                'Не удалось добавить вопрос'
209
            )
210
            return HttpResponseRedirect(reverse('quest:offer_quest'))
211

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.