Exesize

Форк
0
/
views.py 
235 строк · 8.1 Кб
1
import logging
2

3
from django.contrib.auth.mixins import PermissionRequiredMixin, UserPassesTestMixin
4
from django.core.cache import cache
5
from django.http import JsonResponse, FileResponse, HttpResponseRedirect
6
from django.shortcuts import get_object_or_404
7
from django.template.loader import render_to_string
8
from django.urls import reverse_lazy
9
from django.views.generic import TemplateView, ListView, UpdateView, CreateView, DetailView, DeleteView, View
10

11
from config import settings
12
from mainapp import forms
13
from mainapp import tasks
14
from mainapp.forms import CourseFeedbackForm
15
from mainapp.models import News, Courses, Lesson, CourseTeachers, CourseFeedback
16

17
logger = logging.getLogger(__name__)
18

19

20
class ContactsView(TemplateView):
21
    template_name = 'mainapp/contacts.html'
22

23
    def get_context_data(self, **kwargs):
24
        context_data = super().get_context_data(**kwargs)
25
        context_data['contacts'] = [
26
            {
27
                'map': 'https://yandex.ru/map-widget/v1/-/CCUAZHcrhA',
28
                'city': 'Санкт‑Петербург',
29
                'phone': '+7-999-11-11111',
30
                'email': 'geeklab@spb.ru',
31
                'adress': 'территория Петропавловская крепость, 3Ж'
32
            }, {
33
                'map': 'https://yandex.ru/map-widget/v1/-/CCUAZHX3xB',
34
                'city': 'Казань',
35
                'phone': '+7-999-22-22222',
36
                'email': 'geeklab@kz.ru',
37
                'adress': 'территория Кремль, 11, Казань, Республика Татарстан, Россия'
38
            }, {
39
                'map': 'https://yandex.ru/map-widget/v1/-/CCUAZHh9kD',
40
                'city': 'Москва',
41
                'phone': '+7-999-33-33333',
42
                'email': 'geeklab@msk.ru',
43
                'adress': 'Красная площадь, 7, Москва, Россия'
44
            }
45
        ]
46
        return context_data
47

48
    def post(self, *args, **kwargs):
49
        message_body = self.request.POST.get('message_body')
50
        message_from = self.request.user.pk if self.request.user.is_authenticated else None
51
        tasks.send_feedback_to_email.delay(message_body, message_from)
52

53
        return HttpResponseRedirect(reverse_lazy('mainapp:contacts'))
54

55

56
# class CoursesView(TemplateView):
57
#     template_name = 'mainapp/courses_list.html'
58

59

60
class DocSiteView(TemplateView):
61
    template_name = 'mainapp/doc_site.html'
62

63

64
class IndexView(TemplateView):
65
    template_name = 'mainapp/index.html'
66

67

68
class LoginView(TemplateView):
69
    template_name = 'mainapp/login.html'
70

71

72
class NewsListView(ListView):
73
    model = News
74
    paginate_by = 2
75

76
    def get_queryset(self):
77
        return super().get_queryset().filter(deleted=False)
78

79

80
class NewsDetailView(DetailView):
81
    model = News
82

83
    def get_object(self, queryset=None):
84
        return get_object_or_404(News, pk=self.kwargs.get('pk'), deleted=False)
85

86

87
class NewsCreateView(PermissionRequiredMixin, CreateView):
88
    model = News
89
    fields = '__all__'
90
    success_url = reverse_lazy('mainapp:news')
91
    permission_required = ('mainapp.add_news',)
92

93

94
class NewsUpdateView(PermissionRequiredMixin, UpdateView):
95
    model = News
96
    fields = '__all__'
97
    success_url = reverse_lazy('mainapp:news')
98
    permission_required = ('mainapp.change_news',)
99

100

101
class NewsDeleteView(PermissionRequiredMixin, DeleteView):
102
    model = News
103
    success_url = reverse_lazy('mainapp:news')
104
    permission_required = ('mainapp.delete_news',)
105

106

107
# class NewsWithPagination(NewsListView):
108
#
109
#     def get_context_data(self, page, **kwargs):
110
#         context = super().get_context_data(page=page, **kwargs)
111
#         context["page_num"] = page
112
#         return context
113

114

115
class ContactsPageView(TemplateView):
116
    template_name = "mainapp/contacts.html"
117

118
    def get_context_data(self, **kwargs):
119
        context = super(ContactsPageView, self).get_context_data(**kwargs)
120
        if self.request.user.is_authenticated:
121
            context["form"] = forms.CourseFeedbackForm(
122
                user=self.request.user
123
            )
124
        return context
125

126
    # def post(self, *args, **kwargs):
127
    #     if self.request.user.is_authenticated:
128
    #         cache_lock_flag = cache.get(
129
    #             f"mail_feedback_lock_{self.request.user.pk}"
130
    #         )
131
    #
132
    #         if not cache_lock_flag:
133
    #             cache.set(
134
    #                 f"mail_feedback_lock_{self.request.user.pk}",
135
    #                 "lock",
136
    #                 timeout=300,
137
    #             )
138
    #             messages.add_message(
139
    #                 self.request, messages.INFO, f"Message sended"
140
    #             )
141
    #             tasks.send_feedback_mail.delay(
142
    #                 {
143
    #                     "user_id": self.request.POST.get("user_id"),
144
    #                     "message": self.request.POST.get("message"),
145
    #                 }
146
    #             )
147
    #         else:
148
    #             self.message = messages.add_message(self.request, messages.WARNING,
149
    #                                                 f"You can send only one message per 5 minutes", )
150
    #     return HttpResponseRedirect(reverse_lazy("mainapp:contacts"))
151

152

153
class DocSitePageView(TemplateView):
154
    template_name = "mainapp/doc_site.html"
155

156

157
class CoursesListView(TemplateView):
158
    template_name = "mainapp/courses_list.html"
159
    model = Courses
160
    paginate_by = 2
161

162
    def get_context_data(self, **kwargs):
163
        context = super(CoursesListView, self).get_context_data(**kwargs)
164
        context['objects'] = Courses.objects.all()
165

166
        return context
167

168

169
class CourseDetailView(TemplateView):
170
    template_name = "mainapp/courses_detail.html"
171

172
    def get_context_data(self, **kwargs):
173
        context_data = super().get_context_data(**kwargs)
174
        context_data['course_object'] = get_object_or_404(Courses, pk=self.kwargs.get('pk'))
175
        context_data['lessons'] = Lesson.objects.filter(course=context_data['course_object'])
176
        context_data['teachers'] = CourseTeachers.objects.filter(course=context_data['course_object'])
177
        feedback_list_key = f"course_feedback{context_data['course_object'].pk}"
178
        cached_feedback_list = cache.get(feedback_list_key)
179
        if cached_feedback_list is None:
180
            context_data['feedback_list'] = CourseFeedback.objects.filter(course=context_data['course_object'])
181
            cache.set(feedback_list_key, context_data['feedback_list'], timeout=300)
182
        else:
183
            context_data['feedback_list'] = cached_feedback_list
184

185
        if not self.request.user.is_anonymous:
186
            if not CourseFeedback.objects.filter(
187
                    course=context_data["course_object"],
188
                    user=self.request.user).count():
189
                context_data['feedback_form'] = CourseFeedbackForm(
190
                    course=context_data['course_object'],
191
                    user=self.request.user
192
                )
193

194
        return context_data
195

196

197
class CourseFeedbackFormView(CreateView):
198
    model = CourseFeedback
199
    form_class = CourseFeedbackForm
200

201
    def form_valid(self, form):
202
        self.object = form.save()
203
        rendered_card = render_to_string('mainapp/includes/feedback_block.html', context={'item': self.object})
204
        return JsonResponse({'card': rendered_card})
205

206

207
class LogView(UserPassesTestMixin, TemplateView):
208
    template_name = 'mainapp/logs.html'
209

210
    def test_func(self):
211
        return self.request.user.is_superuser
212

213
    def get_context_data(self, **kwargs):
214

215
        context = super(LogView, self).get_context_data(**kwargs)
216
        log_slice = []
217
        logs_line = 1000  # Заданное кол-во строк последних логов
218
        last_line = sum(1 for line in open(settings.LOG_FILE))
219
        with open(settings.LOG_FILE, "r") as log_file:
220
            for i, line in enumerate(log_file):
221
                cnt = (last_line - logs_line)
222
                if i < cnt:
223
                    continue
224
                log_slice.insert(0, f'{i} {line}')
225
            context["logs"] = log_slice
226
        return context
227

228

229
class LogDownloadView(UserPassesTestMixin, View):
230

231
    def test_func(self):
232
        return self.request.user.is_superuser
233

234
    def get(self, *args, **kwargs):
235
        return FileResponse(open(settings.LOG_FILE, "rb"))
236

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

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

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

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