Advertisement
llirik

Untitled

Mar 27th, 2021
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 58.82 KB | None | 0 0
  1. from django.http import HttpResponseRedirect
  2. from .models import Essay, Check_Result, Text, Profile, RUBILNIK, Bad_user, Counter, Block_send_textfield, \
  3. Rating_checker, Rating_writer, Essays_list, Test_question, Answer, Questions_list
  4. from .forms import get_essay, get_check, get_rate, get_answer
  5. from django.shortcuts import render, redirect
  6. from django.utils import timezone
  7. from django.views.generic import View
  8. from django.contrib.auth.models import User
  9.  
  10. import random
  11.  
  12. # Требование авторизации
  13. from django.contrib.auth.decorators import login_required
  14. from django.utils.decorators import method_decorator
  15.  
  16. from datetime import datetime, timedelta
  17.  
  18. from social_django.models import UserSocialAuth
  19. import requests
  20. import json
  21.  
  22. import logging
  23. from Main import my_config
  24. from Site.settings import BASE_DIR
  25.  
  26. import os
  27.  
  28. # from weasyprint import HTML
  29.  
  30.  
  31. # Для картинок:
  32. from PIL import Image
  33. from urllib.request import urlopen
  34.  
  35.  
  36. logger = logging.getLogger(__name__)
  37.  
  38. ADMINS_LIST = my_config.ADMINS_LIST
  39.  
  40.  
  41. def get_current_time():
  42. _time_now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=3))) # получение московского времени
  43. time_now = _time_now.strftime("%d.%m.%Y %H:%M:%S") # пример формата времени: '01.06.2020 03:26:31'
  44. return time_now
  45.  
  46.  
  47. # получение id вк по короткой ссылке
  48. # https://vk.com/dev/utils.resolveScreenName
  49. def _get_vk_user_id(VK_SHORT_ID):
  50. ACCESS_TOKEN = my_config.VK_AUTH_SERVICE_ACCESS_KEY
  51. API_VERSION = '5.21'
  52. vk_profile_response = requests.get(
  53. f'https://api.vk.com/method/utils.resolveScreenName?screen_name={VK_SHORT_ID}&access_token={ACCESS_TOKEN}&v={API_VERSION}').text
  54. dict_vk_profile_response = json.loads(vk_profile_response)
  55. try:
  56. vk_profile_id = dict_vk_profile_response['response']['object_id']
  57. except:
  58. return 'ERROR@'
  59. return vk_profile_id
  60.  
  61.  
  62. # получение авы вк
  63. # https://vk.com/dev/users.get
  64. def _get_vk_user_profile_photo(VK_ID, ACCESS_TOKEN, photo_size):
  65. API_VERSION = '5.122'
  66. vk_profile_response = requests.get(
  67. f'https://api.vk.com/method/users.get?user_ids={VK_ID}&fields={photo_size}&access_token={ACCESS_TOKEN}&v={API_VERSION}').text
  68. dict_vk_profile_response = json.loads(vk_profile_response)
  69. try:
  70. vk_profile_photo = dict_vk_profile_response['response'][0][photo_size]
  71. except:
  72. return 'ERROR@'
  73. return vk_profile_photo
  74.  
  75.  
  76. def get_url_full_vk_user_profile_photo(VK_SHORT_ID, photo_size):
  77. try:
  78. _is_error = False
  79. user_id_vk = _get_vk_user_id(VK_SHORT_ID)
  80. if user_id_vk != 'ERROR@':
  81. extra_data = UserSocialAuth.objects.get(uid=user_id_vk).extra_data
  82. else:
  83. logger.error(
  84. f': {VK_SHORT_ID} ошибка получения id vk из короткого имени пользователя! в get_url_full_vk_user_profile_photo()')
  85. return 'ERROR@'
  86. except:
  87. if VK_SHORT_ID in ADMINS_LIST:
  88. print(f'{VK_SHORT_ID}, добро пожаловать. Вы — админ!')
  89. return 'ADMIN@'
  90. else:
  91. logger.error(
  92. f': {VK_SHORT_ID} ошибка получения авы из ВК профиля пользователя! в get_url_full_vk_user_profile_photo()')
  93. return 'ERROR@'
  94. if extra_data['id'] == user_id_vk: # не знаю зачем это, но пусть будет
  95. access_token_vk = extra_data['access_token']
  96. else:
  97. logger.error(f': {VK_SHORT_ID} dict_extra_data[\'id\'] != user_id_vk! в get_url_full_vk_user_profile_photo()')
  98.  
  99. return 'ERROR@'
  100. url_vk_profile_photo = _get_vk_user_profile_photo(user_id_vk, access_token_vk, photo_size)
  101. if url_vk_profile_photo == 'ERROR@':
  102. logger.error(
  103. f': {VK_SHORT_ID} ошибка получения авы из ВК профиля пользователя! в get_url_full_vk_user_profile_photo()')
  104.  
  105. return 'ERROR@'
  106. return url_vk_profile_photo
  107.  
  108.  
  109. # не работает :(
  110. def func_is_send_textarea_blocked():
  111. return Block_send_textfield.objects.all().order_by('-id').get()
  112.  
  113.  
  114. # Вывод текста недели со всей информацией об авторе
  115. def get_text_and_author_info(request):
  116. get_text = Text.objects.all()
  117. text = get_text.order_by("-id")[0:1].get()
  118.  
  119. text_parts = text.Body.split('\n')
  120. text_parts = [x for x in text_parts if x not in [None, '\n', '\r', '']]
  121.  
  122. text_week_n_author_without_star = ''
  123. if '*' in text.Author:
  124. text_week_n_author_without_star = text.Author.replace('*', '')
  125.  
  126. new_Author_description = ''
  127. if text.Author_description_bold != '':
  128. if text.Author_description_bold in text.Author_description:
  129. new_Author_description = text.Author_description.replace(text.Author_description_bold, '')
  130. else:
  131. logger.error(
  132. f': {request.user} text.Author_description не содержит в себе text.Author_description_bold')
  133. else:
  134. logger.warning(f': {request.user} text.Author_description_bold пуст в /send')
  135.  
  136. return text, text_parts, text_week_n_author_without_star, new_Author_description
  137.  
  138.  
  139. def rating_functions(current_essay, last_check, profile_of_essay, profile):
  140.  
  141. new_essay_rating = Rating_writer()
  142. new_essay_rating.user = current_essay.user
  143. new_essay_rating.rating_of_rater = profile.rating
  144. new_essay_rating.essay_rating = round(last_check.score, 2)
  145. new_essay_rating.save()
  146.  
  147. essay_rating = Rating_writer.objects.filter(user=current_essay.user)
  148. e_sum = 0
  149. num_of_checks = 0
  150. sum_score = 0
  151. true_num_of_check = 0
  152. for e_rate in essay_rating:
  153. # Тут формула 228, которая увеличивает значимость проверки в зависимости от рейтинга проверяющего!
  154. e_sum += e_rate.essay_rating * ((e_rate.rating_of_rater ** 2) / 50 + 1)
  155. sum_score += e_rate.essay_rating
  156. num_of_checks += ((e_rate.rating_of_rater ** 2) / 50 + 1)
  157. true_num_of_check += 1
  158. average_essay_rating = e_sum / num_of_checks
  159. average_score = sum_score / true_num_of_check
  160. profile_of_essay.essay_rating = round(average_essay_rating * 0.2, 2)
  161. profile_of_essay.average_score = round(average_score, 2)
  162. profile_of_essay.save()
  163.  
  164. final_score = (1.2 * profile_of_essay.checker_rating + 0.8 * profile_of_essay.essay_rating) / 2
  165.  
  166. if final_score > profile_of_essay.rating / 2:
  167. profile_of_essay.rating += round(0.1 * (final_score - profile_of_essay.rating / 2), 2)
  168. else:
  169. profile_of_essay.rating -= round(0.1 * (profile_of_essay.rating / 2 - final_score), 2)
  170. if profile_of_essay.rating > 10:
  171. profile_of_essay.rating = 10
  172. if profile_of_essay.rating < 0:
  173. profile_of_essay.rating = 0
  174. profile_of_essay.save()
  175.  
  176.  
  177. def get_user_profile_avatars(profile, request) -> None:
  178. vk_profile_photo_200 = profile.avatar_200
  179. vk_profile_photo_50 = profile.avatar_50
  180. if (vk_profile_photo_200 is None or vk_profile_photo_200 == '') and (vk_profile_photo_50 is None or vk_profile_photo_50 == ''):
  181. logger.info(f': {request.user} впервые зашёл на сайт')
  182. profile.avatar_200 = get_url_full_vk_user_profile_photo(request.user.username, 'photo_200')
  183. profile.avatar_50 = get_url_full_vk_user_profile_photo(request.user.username, 'photo_50')
  184. profile.save()
  185.  
  186.  
  187. class Send(View):
  188. # Требуется авторизация, чтобы фукнция внутри класса запустилась
  189. @method_decorator(login_required)
  190. def get(self, request):
  191. logger.info(f': {request.user} открыта страница /send')
  192. what_time = RUBILNIK.objects.all().order_by('-id').get()
  193. profile = Profile.objects.get(user=request.user)
  194. get_user_profile_avatars(profile, request)
  195. if what_time.sent_check == 1 and profile.ban == 0 and profile.rating >= 1.5:
  196. # Определение этапа для отображения в шапке (пишем сочинения или проверяем?)
  197. which_step = 'Этап сдачи сочинений'
  198. which_step_title = 'этап 1/3'
  199.  
  200. form = get_essay()
  201.  
  202. data = {
  203. 'form': form,
  204. 'profile': profile,
  205. 'which_step': which_step,
  206. 'which_step_title': which_step_title,
  207. 'func_is_send_textarea_blocked': func_is_send_textarea_blocked(),
  208. }
  209.  
  210.  
  211. # получение всей информации о тексте недели и его авторе
  212. text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
  213. request)
  214. data['text'] = text
  215. data['text_parts'] = text_parts
  216. data['text_week_n_author_without_star'] = text_week_n_author_without_star
  217. data['new_Author_description'] = new_Author_description
  218.  
  219.  
  220. if_soch_already_send = False
  221. if Essay.objects.filter(user=request.user, text=text).exists():
  222. if_soch_already_send = True
  223. essay = Essay.objects.get(user=request.user, text=text)
  224. _sent_time = essay.time
  225. sent_time = _sent_time.strftime("%d.%m.%Y %H:%M:%S")
  226. new_sent_time = datetime.strptime(str(sent_time), "%d.%m.%Y %H:%M:%S") + timedelta(hours=3)
  227.  
  228. sent_essay = essay.Body.split('\n')
  229. sent_essay = [x for x in sent_essay if x not in [None, '\n', '\r', '']]
  230.  
  231. data['sent_essay'] = sent_essay
  232. data['sent_time'] = f'На {text.week_number} неделе Вами уже было отправлено сочинение {new_sent_time.strftime("%d.%m.%Y {} %H:%M:%S".format("в"))} (МСК):'
  233.  
  234. data['if_soch_already_send'] = if_soch_already_send
  235.  
  236. elif profile.rating < 1.5:
  237. return redirect('/test')
  238. else:
  239. return redirect('/')
  240. return render(request, 'send.html', data)
  241.  
  242. def post(self, request):
  243. logger.info(f': {request.user} отправлена форма со страницы /send')
  244.  
  245. which_step_title = 'этап 1/3'
  246.  
  247. data = {}
  248.  
  249. # получение всей информации о тексте недели и его авторе
  250. text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
  251. request)
  252. data['text'] = text
  253. data['text_parts'] = text_parts
  254. data['text_week_n_author_without_star'] = text_week_n_author_without_star
  255. data['new_Author_description'] = new_Author_description
  256.  
  257.  
  258. form = get_essay(request.POST, initial={'Title': text.Title, 'text': text})
  259. profile = Profile.objects.get(user=request.user)
  260. users_essays = Essay.objects.filter(user=request.user, text=text)
  261. if users_essays.count() > 0:
  262. if_essay = users_essays.order_by('-id').get()
  263. else:
  264. if_essay = None
  265. # Надо сделать проверку на уникальность сочина к тексту другим способом.
  266. # Сейчас при обновлении сохранятеся второй сочин т.к. второе условие выполняется....
  267. if (if_essay == None) or (if_essay.text != text):
  268. print(form.is_valid(), users_essays.count())
  269. if form.is_valid() and users_essays.count() == 0:
  270. form.save()
  271.  
  272. essay_sent_for_edit = True
  273. text.Number_of_essays = Essay.objects.filter(text=text).count() + 1
  274. text.save()
  275.  
  276. # Выдача номера сочинению по этому тексту
  277. essay = Essay.objects.all().order_by("-id")[0:1].get()
  278. essay.number = text.Number_of_essays
  279. essay.time = timezone.now()
  280. essay.user = request.user
  281. essay.text = text
  282. Body = str(essay.Body)
  283. essay.Title = Body[0:30]
  284. essay.save()
  285.  
  286. # Выдача номера сдавшему сочин
  287. profile = Profile.objects.get(user=request.user)
  288. profile.queue = text.Number_of_essays
  289. profile.sent = text.id
  290. profile.check_number = 0
  291. profile.save()
  292.  
  293. # Закрепление сочина за юзером
  294. profile = Profile.objects.get(user=request.user)
  295. profile.number_of_essays = Essay.objects.filter(user=request.user).count()
  296. profile.essays.add(essay)
  297. profile.save()
  298.  
  299. numbur_of_soch_for_google_sheets = Essay.objects.all().count()
  300. # upload_soch_to_google_sheets(essay.Title, essay.Body, essay.number, request.user)
  301.  
  302. logger.info(f'{request.user} отправил сочинение : {essay.Body} - ({essay.Title})')
  303. return redirect('/send')
  304.  
  305. else:
  306. return redirect('/send')
  307. else:
  308. error = 'Вы уже отправили сочинение на этой неделе!'
  309.  
  310. data['already_sent_error'] = error
  311. data['form'] = form
  312. data['which_step_title'] = which_step_title
  313. data['profile'] = profile
  314.  
  315. return render(request, 'send.html', data)
  316.  
  317. # Вот время сдачи, но так не работает норм формамт
  318. this_essay = Essay.objects.get(user=request.user, text=text)
  319. _sent_time = this_essay.time
  320. sent_time = _sent_time.strftime("%d.%m.%Y %H:%M:%S")
  321.  
  322. data['form'] = form
  323. data['profile'] = profile
  324. data['which_step_title'] = which_step_title
  325. data['new_sent_time'] = None
  326. data['essay_sent_for_edit'] = essay_sent_for_edit
  327.  
  328. if Essay.objects.filter(user=request.user, text=text).exists():
  329. new_sent_time = datetime.strptime(str(sent_time), "%d.%m.%Y %H:%M:%S") + timedelta(hours=3)
  330. new_sent_time = f'Вы отправили сочинение {new_sent_time.strftime("%d.%m.%Y {} %H:%M:%S".format("в"))} (МСК)'
  331. data['new_sent_time'] = new_sent_time
  332.  
  333. return render(request, 'send.html', data)
  334.  
  335.  
  336. class Edit(View):
  337. def get(self, request):
  338. get_text = Text.objects.all()
  339. text = get_text.order_by("-id")[0:1].get()
  340. profile = Profile.objects.get(user=request.user)
  341. get_user_profile_avatars(profile, request)
  342. what_time = RUBILNIK.objects.all().order_by('-id').get()
  343.  
  344. if what_time.sent_check == 1 and profile.ban == 0 and Essay.objects.filter(text=text,
  345. user=request.user).exists():
  346. essay = Essay.objects.get(text=text, user=request.user)
  347. form = get_essay(initial={'Body': essay.Body})
  348. which_step = 'Этап сдачи сочинений'
  349. which_step_title = 'этап 1/3'
  350.  
  351. data = {
  352. 'form': form,
  353. 'profile': profile,
  354. 'which_step': which_step,
  355. 'which_step_title': which_step_title,
  356. 'func_is_send_textarea_blocked': func_is_send_textarea_blocked(),
  357. }
  358.  
  359.  
  360. # получение всей информации о тексте недели и его авторе
  361. text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
  362. request)
  363. data['text'] = text
  364. data['text_parts'] = text_parts
  365. data['text_week_n_author_without_star'] = text_week_n_author_without_star
  366. data['new_Author_description'] = new_Author_description
  367.  
  368.  
  369. return render(request, 'edit.html', data)
  370. else:
  371. return redirect('/send')
  372.  
  373.  
  374. def post(self, request):
  375. get_text = Text.objects.all()
  376. text = get_text.order_by("-id")[0:1].get()
  377. profile = Profile.objects.get(user=request.user)
  378. what_time = RUBILNIK.objects.all().order_by('-id').get()
  379.  
  380. if what_time.sent_check == 1 and profile.ban == 0 and Essay.objects.filter(text=text,
  381. user=request.user).exists():
  382. essay = Essay.objects.get(text=text, user=request.user)
  383. form = get_essay(request.POST, initial={'Body': essay.Body})
  384.  
  385. essay.Body = request.POST.get("Body")
  386. essay.time = timezone.now()
  387. body = str(essay.Body)
  388. essay.Title = body[0:30]
  389. essay.save()
  390.  
  391. which_step = 'Этап сдачи сочинений'
  392. which_step_title = 'этап 1/3'
  393.  
  394. data = {
  395. 'form': form,
  396. 'profile': profile,
  397. 'which_step': which_step,
  398. 'which_step_title': which_step_title,
  399. 'func_is_send_textarea_blocked': func_is_send_textarea_blocked(),
  400. }
  401.  
  402. # получение всей информации о тексте недели и его авторе
  403. text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
  404. request)
  405. data['text'] = text
  406. data['text_parts'] = text_parts
  407. data['text_week_n_author_without_star'] = text_week_n_author_without_star
  408. data['new_Author_description'] = new_Author_description
  409.  
  410.  
  411. return redirect('/send')# render(request, 'edit.html', data)
  412. else:
  413. return redirect('/send')
  414.  
  415.  
  416. class Check(View):
  417. # Требуется авторизация, чтобы фукнция внутри класса запустилась
  418. @method_decorator(login_required)
  419. def get(self, request):
  420. profile = Profile.objects.get(user=request.user)
  421. if Essay.objects.filter(user=request.user, text=Text.objects.order_by("-id")[0:1].get()).exists():
  422. get_user_profile_avatars(profile, request)
  423. what_time = RUBILNIK.objects.all().order_by('-id').get()
  424.  
  425. if what_time.sent_check == 0 and profile.ban == 0 and profile.rating >= 1.5:
  426. logger.info(f': {request.user} открыта страница /check')
  427.  
  428. which_step_title = 'этап 2/3'
  429.  
  430. text = Text.objects.order_by('-id')[0:1].get()
  431. # Вывод сочина на проверку
  432. if Essays_list.objects.filter(user=request.user).count() == 0:
  433. get_essay = Essay.objects.filter(text=text)
  434. number_of_essays = Essay.objects.filter(text=text).count()
  435.  
  436. _distribution_chances = []
  437. for essay in get_essay:
  438. profile_of_essay = Profile.objects.get(user=essay.user)
  439. # 0.1 чтоб деления на 0 не было!
  440. chance = random.random()*(5 / (abs(profile.rating - profile_of_essay.rating)+0.1))
  441. _distribution_chances.append([chance, essay])
  442.  
  443. distribution_chances = sorted(_distribution_chances, reverse=True)
  444. print('> > > ', distribution_chances)
  445. for chance, essay in distribution_chances:
  446. if essay.user != profile.user:
  447. new_essay = Essays_list()
  448. new_essay.user = profile.user
  449. new_essay.essay = essay
  450. essay.checked += 1
  451. essay.save()
  452. new_essay.save()
  453.  
  454. # Получение массива с 4 сочинами из индивидуального списка (в правильном ли порядке чекни)
  455. essay = []
  456. for e in Essays_list.objects.filter(user=request.user).order_by("id"):
  457. if e.essay.checked < 4:
  458. essay.append(e.essay)
  459. if len(essay) > 5:
  460. break
  461.  
  462. profile.check_number = Check_Result.objects.filter(checker=request.user, Text=text).count()
  463. if profile.check_number < 3 and Essay.objects.filter(text=text, user=request.user).exists():
  464. current_essay = essay[profile.check_number]
  465. else:
  466. current_essay = None
  467. if current_essay is not None:
  468. soch_to_summernote = Essay.objects.get(id=current_essay.id).Body.split('\n')
  469. soch_to_summernote = ''.join(f'<p>{x}</p>' for x in soch_to_summernote if x not in [None, '\n', '\r', ''])
  470.  
  471. form = get_check(initial={'summernote_editor': soch_to_summernote})
  472.  
  473. else:
  474. form = get_check
  475.  
  476. data = {
  477. 'form': form,
  478. 'profile': profile,
  479. 'essay': essay,
  480. 'which_step_title': which_step_title,
  481. 'current_essay': current_essay,
  482. 'content_marks_table': my_config.CHECK_ESSAY_TABLE,
  483. }
  484.  
  485. # получение всей информации о тексте недели и его авторе
  486. text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
  487. request)
  488. data['text'] = text
  489. data['text_parts'] = text_parts
  490. data['text_week_n_author_without_star'] = text_week_n_author_without_star
  491. data['new_Author_description'] = new_Author_description
  492.  
  493. essay0_parts = str(essay[0].Body).split('\n')
  494. essay1_parts = str(essay[1].Body).split('\n')
  495. essay2_parts = str(essay[2].Body).split('\n')
  496.  
  497. if Check_Result.objects.filter(essay=essay[0], checker=request.user).exists():
  498. essay0_parts = str(Check_Result.objects.get(essay=essay[0], checker=request.user).summernote_editor).split('\n')
  499. if Check_Result.objects.filter(essay=essay[1], checker=request.user).exists():
  500. essay1_parts = str(Check_Result.objects.get(essay=essay[1], checker=request.user).summernote_editor).split('\n')
  501. if Check_Result.objects.filter(essay=essay[2], checker=request.user).exists():
  502. essay2_parts = str(Check_Result.objects.get(essay=essay[2], checker=request.user).summernote_editor).split('\n')
  503.  
  504. essay0_parts = [x for x in essay0_parts if x not in [None, '\n', '\r', '']]
  505. essay1_parts = [x for x in essay1_parts if x not in [None, '\n', '\r', '']]
  506. essay2_parts = [x for x in essay2_parts if x not in [None, '\n', '\r', '']]
  507.  
  508. current_essay_number = int(profile.check_number)
  509. data['current_essay_number'] = current_essay_number
  510.  
  511. data['essay0_parts'] = essay0_parts
  512. data['essay1_parts'] = essay1_parts
  513. data['essay2_parts'] = essay2_parts
  514.  
  515. if Check_Result.objects.filter(checker=request.user, Text=text).count() > 2:
  516. print(essay)
  517. try:
  518. data['next_essay'] = essay[3]
  519. except IndexError:
  520. pass
  521. elif profile.rating < 1.5:
  522. return redirect('/test')
  523. else:
  524. return redirect('/')
  525.  
  526. return render(request, 'check.html', data)
  527. else:
  528. if Essays_list.objects.filter(user=request.user).count() == 0:
  529. text = Text.objects.order_by('-id')[0:1].get()
  530. get_essay = Essay.objects.filter(text=text)
  531. number_of_essays = Essay.objects.filter(text=text).count()
  532.  
  533. _distribution_chances = []
  534. for essay in get_essay:
  535. profile_of_essay = Profile.objects.get(user=essay.user)
  536. # 0.1 чтоб деления на 0 не было!
  537. chance = random.random() * (5 / (abs(profile.rating - profile_of_essay.rating) + 0.1))
  538. _distribution_chances.append([chance, essay])
  539.  
  540. distribution_chances = sorted(_distribution_chances, reverse=True)
  541. for chance, essay in distribution_chances:
  542. if essay.user != profile.user:
  543. new_essay = Essays_list()
  544. new_essay.user = profile.user
  545. new_essay.essay = essay
  546. essay.checked += 1
  547. essay.save()
  548. new_essay.save()
  549. next_essay = Essays_list.objects.filter(user=request.user).order_by("id")[0:1].get()
  550. next_essay_number = next_essay.essay.number
  551. print(">>> ", next_essay_number)
  552. return redirect(f'/check_optional/{next_essay_number}')
  553.  
  554. def post(self, request):
  555. logger.info(f': {request.user} отправлена форма со страницы /check')
  556.  
  557. which_step_title = 'этап 2/3'
  558. form = get_check(request.POST)
  559. profile = Profile.objects.get(user=request.user)
  560.  
  561. # Подгружаются сочины из БД
  562. essay = []
  563. for e in Essays_list.objects.filter(user=request.user).order_by("id"):
  564. if e.essay.checked < 4:
  565. essay.append(e.essay)
  566. if len(essay) > 5:
  567. break
  568.  
  569. data = {
  570. 'form': form,
  571. 'profile': profile,
  572. 'which_step_title': which_step_title,
  573. 'essay': essay,
  574. }
  575.  
  576. # получение всей информации о тексте недели и его авторе
  577. text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(
  578. request)
  579. data['text'] = text
  580. data['text_parts'] = text_parts
  581. data['text_week_n_author_without_star'] = text_week_n_author_without_star
  582. data['new_Author_description'] = new_Author_description
  583.  
  584. current_essay_number = Essay.objects.filter(text=text).count()
  585. data['current_essay_number'] = current_essay_number
  586.  
  587.  
  588. try:
  589. data['next_essay'] = essay[3]
  590. except IndexError:
  591. pass
  592.  
  593. _essays_count = Essay.objects.filter(text=text).count()
  594. profile.check_number = Check_Result.objects.filter(checker=request.user, Text=text).count()
  595. if form.is_valid() and _essays_count - 1 > profile.check_number and profile.check_number < 3:
  596. form.save()
  597.  
  598. # Здесь будет закрпеление проверок за юзером
  599. save_check = Check_Result.objects.all()
  600. last_check = save_check.order_by("-id")[0:1].get()
  601. last_check.Text = text
  602. last_check.checker = request.user
  603. profile.checks.add(last_check)
  604. profile.total_checked = Check_Result.objects.filter(checker=request.user).count()
  605.  
  606. # Счётчик баллов
  607. ki_to_upload = [last_check.k1, last_check.k2, last_check.k3, last_check.k4, last_check.k5, last_check.k6, \
  608. last_check.k7, last_check.k8, last_check.k9, last_check.k10, last_check.k11, last_check.k12]
  609.  
  610. total_mark = 0
  611. for ki in ki_to_upload:
  612. total_mark += ki
  613.  
  614. last_check.score = total_mark
  615. last_check.save()
  616.  
  617. if profile.check_number == 2 and _essays_count > 3:
  618. last_check.essay = essay[2]
  619. profile.check_number = profile.check_number + 1
  620. profile.save()
  621. current_essay = essay[2]
  622. elif profile.check_number == 1 and _essays_count > 2:
  623. last_check.essay = essay[1]
  624. profile.check_number = profile.check_number + 1
  625. profile.save()
  626. current_essay = essay[1]
  627. elif profile.check_number == 0 and _essays_count > 1:
  628. last_check.essay = essay[0]
  629. profile.check_number = profile.check_number + 1
  630. profile.save()
  631. current_essay = essay[0]
  632. last_check.essay = current_essay
  633. last_check.save()
  634.  
  635. check = Check_Result.objects.order_by('id')[0:1].get()
  636. soch_author = check.essay.user
  637.  
  638. profile_of_essay = Profile.objects.filter(user=current_essay.user).order_by('-id')[0:1].get()
  639.  
  640. rating_functions(current_essay, last_check, profile_of_essay, profile)
  641.  
  642. k_comments_to_upload = [last_check.k1_comment, last_check.k2_comment, last_check.k3_comment, \
  643. last_check.k4_comment, last_check.k5_comment, last_check.k6_comment, \
  644. last_check.k7_comment, last_check.k8_comment, last_check.k9_comment, \
  645. last_check.k10_comment, last_check.k11_comment, last_check.k12_comment]
  646.  
  647.  
  648. # upload_check_to_google_sheets(last_check.essay, soch_author, last_check.score, request.user, ki_to_upload,
  649.  
  650. logger.info(
  651. f'{request.user} отправил проверку для {soch_author} : баллы: {ki_to_upload}; комментарии: {k_comments_to_upload}')
  652.  
  653.  
  654. else:
  655. checked_all = 'Вы уже проверили свои 3 сочинения'
  656. data['checked_all'] = checked_all
  657. return render(request, 'check.html', data)
  658. if profile.check_number < 3:
  659. data['current_essay'] = current_essay
  660.  
  661.  
  662. return redirect('/check')
  663.  
  664.  
  665. class Optional(View):
  666. def essay_list(self, request) -> list:
  667. # Подгружаются сочины из БД
  668. essay = []
  669. i = 0
  670. for e in Essays_list.objects.filter(user=request.user):
  671. if Essay.objects.get(id=e.essay.id).checked < 3:
  672. essay.append(e.essay)
  673. if i == 2:
  674. break
  675. i += 1
  676. return essay
  677.  
  678. def get(self, request, next_essay_id):
  679. profile = Profile.objects.get(user=request.user)
  680. get_user_profile_avatars(profile, request)
  681. what_time = RUBILNIK.objects.all().order_by('-id').get()
  682. text = Text.objects.order_by('-id')[0:1].get()
  683. checked_this_week = Check_Result.objects.filter(checker=request.user, Text=text).count()
  684. can_go = False
  685. if checked_this_week > 2 or not Essay.objects.filter(user=request.user, text=text).exists():
  686. can_go = True
  687. logger.info(f': {request.user} открыта страница /check_optional')
  688. if what_time.sent_check == 0 and profile.ban == 0 and profile.rating >= 1.5 and can_go:
  689. text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(request)
  690. current_essay = Essay.objects.get(number=next_essay_id, text=text)
  691.  
  692. if not Check_Result.objects.filter(checker=request.user, essay=current_essay).exists():
  693. soch_to_summernote = Essay.objects.get(id=current_essay.id).Body.split('\n')
  694. soch_to_summernote = ''.join(f'<p>{x}</p>' for x in soch_to_summernote if x not in [None, '\n', '\r', ''])
  695. form = get_check(initial={'summernote_editor': soch_to_summernote})
  696. essay_to_show = None
  697. else:
  698. form = None
  699. essay_to_show = Check_Result.objects.get(essay=current_essay, checker=request.user).summernote_editor
  700. which_step_title = 'этап 2/3: дополнительные проверки'
  701.  
  702. print(essay_to_show)
  703. # essays = self.essay_list(request)
  704.  
  705. user_checked = Check_Result.objects.filter(checker=request.user, Text=text).count()
  706. num_of_essays = Essay.objects.filter(text=text).count()
  707.  
  708. num_of_essays_ostatok = num_of_essays - user_checked - 1
  709. if not Essay.objects.filter(user=request.user, text=text).exists():
  710. num_of_essays_ostatok += 1
  711.  
  712. essay_parts = str(current_essay.Body).split('\n')
  713. essay_parts = [x for x in essay_parts if x not in [None, '\n', '\r', '']]
  714.  
  715. data = {
  716. 'profile': profile,
  717. 'current_essay': current_essay,
  718. 'essay_parts': essay_parts,
  719. 'essay_to_show': essay_to_show,
  720. #'essay_to_show_parts': essay_to_show_parts,
  721. 'which_step_title': which_step_title,
  722. 'user_checked': user_checked,
  723. 'num_of_essays': num_of_essays - 1,
  724. 'num_of_essays_ostatok': num_of_essays_ostatok,
  725. 'content_marks_table': my_config.CHECK_ESSAY_TABLE,
  726. }
  727.  
  728.  
  729. if current_essay.user == request.user:
  730. form = None
  731. data['your_essay_message'] = 'Это ваше сочинение лол'
  732. data['form'] = form
  733. # получение всей информации о тексте недели и его авторе
  734. data['text'] = text
  735. data['text_parts'] = text_parts
  736. data['text_week_n_author_without_star'] = text_week_n_author_without_star
  737. data['new_Author_description'] = new_Author_description
  738.  
  739.  
  740. # Подгружаются сочины из БД
  741. text = Text.objects.order_by('-id')[0:1].get()
  742. essay = []
  743. i = 0
  744. for e in Essays_list.objects.filter(user=request.user):
  745. essay.append(e.essay)
  746. if e.essay == Essay.objects.get(text=text, number=int(next_essay_id)):
  747. num_of_current_essay_in_list = i
  748. i += 1
  749.  
  750. try:
  751. next_essay = essay[num_of_current_essay_in_list + 1]
  752. data['next_essay'] = next_essay
  753. except IndexError:
  754. pass
  755.  
  756. if num_of_current_essay_in_list > 0:
  757. previous_essay = essay[num_of_current_essay_in_list - 1]
  758. data['previous_essay'] = previous_essay
  759.  
  760. return render(request, 'check_optional.html', data)
  761. else:
  762. return redirect('/')
  763.  
  764. def post(self, request, next_essay_id):
  765. logger.info(f': {request.user} отправлена форма со страницы /check_optional')
  766. # получение всей информации о тексте недели и его авторе
  767. text, text_parts, text_week_n_author_without_star, new_Author_description = get_text_and_author_info(request)
  768. essays = self.essay_list(request)
  769. form = get_check(request.POST)
  770.  
  771. profile = Profile.objects.get(user=request.user)
  772. if form.is_valid():
  773. form.save()
  774. current_essay = Essay.objects.get(number=next_essay_id, text=text)
  775. body = str(current_essay.Body)
  776. current_essay.Title = body[0:30]
  777. # Здесь будет закрпеление проверок за юзером
  778. last_check = Check_Result.objects.order_by("-id")[0:1].get()
  779. last_check.Text = text
  780. last_check.checker = request.user
  781. last_check.essay = current_essay
  782. profile.checks.add(last_check)
  783. profile.total_checked = Check_Result.objects.filter(checker=request.user).count()
  784.  
  785. # Счётчик баллов
  786. ki_to_upload = [last_check.k1, last_check.k2, last_check.k3, last_check.k4, last_check.k5, last_check.k6, \
  787. last_check.k7, last_check.k8, last_check.k9, last_check.k10, last_check.k11, last_check.k12]
  788.  
  789. total_mark = 0
  790. for ki in ki_to_upload:
  791. total_mark += ki
  792.  
  793. last_check.score = total_mark
  794. last_check.save()
  795.  
  796. check = Check_Result.objects.order_by('id')[0:1].get()
  797. soch_author = check.essay.user
  798. k_comments_to_upload = [last_check.k1_comment, last_check.k2_comment, last_check.k3_comment, \
  799. last_check.k4_comment, last_check.k5_comment, last_check.k6_comment, \
  800. last_check.k7_comment, last_check.k8_comment, last_check.k9_comment, \
  801. last_check.k10_comment, last_check.k11_comment, last_check.k12_comment]
  802.  
  803. logger.info(
  804. f'{request.user} отправил проверку (optional) для {soch_author} : баллы: {ki_to_upload}; комментарии: {k_comments_to_upload}')
  805.  
  806. profile_of_essay = Profile.objects.filter(user=current_essay.user).order_by('-id')[0:1].get()
  807. print('profile_of_essay - ', profile_of_essay)
  808.  
  809. rating_functions(current_essay, last_check, profile_of_essay, profile)
  810.  
  811. return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
  812.  
  813.  
  814. def login(request):
  815. logger.info(f': {request.user} открыта страница /login')
  816. return render(request, 'auth/login.html')
  817.  
  818.  
  819. # Требуется авторизация, чтобы фукнция запустилась
  820. @login_required
  821. def home(request): # бывшая IndexView функция
  822. logger.info(f': {request.user} открыта страница /')
  823. print('request.user.username:', request.user.username)
  824. profile = Profile.objects.get(user=request.user)
  825. get_user_profile_avatars(profile, request)
  826.  
  827. what_time = RUBILNIK.objects.all().order_by('-id').get()
  828. if what_time.sent_check == 0:
  829. time_is = None
  830. else:
  831. time_is = 1
  832.  
  833. data = {
  834. 'time_is': time_is,
  835. 'profile': profile,
  836. }
  837. if profile.ban == 1:
  838. data['ban_msg'] = 'Вам бан'
  839. return render(request, 'homepage.html', data)
  840.  
  841.  
  842. # Требуется авторизация, чтобы фукнция запустилась
  843. @login_required
  844. def profile(request): # возможно надо переделать это в класс
  845. logger.info(f': {request.user} открыта страница /profile')
  846. which_step_title = request.user.username
  847. step_is = bad_user = week_number = ''
  848. if request.user.is_superuser:
  849. what_time = RUBILNIK.objects.all().order_by('-id').get()
  850. text = Text.objects.order_by('-id')[0:1].get()
  851. week_number = text.week_number - 1
  852. if what_time.sent_check == 0:
  853. step_is = 'Этап сдачи проверок'
  854. else:
  855. step_is = 'Этап сдачи сочинений'
  856. # Список юзеров, не проверивших все 3 сочина
  857. bad_user = Bad_user.objects.order_by('-id')[0:1].get()
  858.  
  859. # Стата из профиля
  860. profile = Profile.objects.get(user=request.user)
  861. get_user_profile_avatars(profile, request)
  862.  
  863. # Дата отправки первого сочинения
  864. if profile.essays.count() > 0:
  865. first_essay = profile.essays.order_by('id')[0:1].get()
  866. date_of_first_essay = first_essay.time
  867. user_with_0_sochs = False
  868. else:
  869. # date_of_first_essay = 'вы ещё не писали сочинений'
  870. user_with_0_sochs = True
  871. date_of_first_essay = ''
  872.  
  873. data = {
  874. 'date_of_first_essay': date_of_first_essay,
  875. 'step_is': step_is,
  876. 'which_step_title': which_step_title,
  877. 'profile': profile,
  878. 'admin': request.user.is_superuser,
  879. 'bad_user': bad_user,
  880. 'week_number': week_number,
  881. 'user_with_0_sochs': user_with_0_sochs,
  882. }
  883.  
  884. return render(request, 'profile.html', data)
  885.  
  886.  
  887. # Требуется авторизация, чтобы фукнция запустилась
  888. class Look(View):
  889. def work_please(self, request):
  890. which_step_title = 'получение проверок'
  891. get_text = Text.objects.all()
  892. text = get_text.order_by("-id")[0:1].get()
  893. essay = Essay.objects.get(user=request.user, text=text)
  894. checks = Check_Result.objects.filter(essay=essay).order_by("id")
  895.  
  896. return get_text, text, essay, checks, which_step_title
  897.  
  898. # Требуется авторизация, чтобы фукнция внутри класса запустилась
  899. @method_decorator(login_required)
  900. def get(self, request):
  901. logger.info(f': {request.user} открыта страница /look')
  902. profile = Profile.objects.get(user=request.user)
  903. get_user_profile_avatars(profile, request)
  904. if profile.ban == 0:
  905. get_text, text, essay, checks, which_step_title = self.work_please(request)
  906.  
  907. form = get_rate
  908. rated_list = []
  909. for rate in Rating_checker.objects.filter(user=request.user, text=text):
  910. rated_list.append(rate.number)
  911.  
  912. essay_parts = essay.Body.split('\n')
  913. essay_parts = [x for x in essay_parts if x not in [None, '\n', '\r', '']]
  914.  
  915. data = {
  916. 'rated_list': rated_list,
  917. 'form': form,
  918. 'profile': profile,
  919. 'essay': essay,
  920. 'checks': checks,
  921. 'which_step_title': which_step_title,
  922. 'essay_parts': essay_parts,
  923. }
  924.  
  925. return render(request, 'look.html', data)
  926. else:
  927. return redirect('/')
  928.  
  929.  
  930. def post(self, request):
  931. get_text, text, essay, checks, which_step_title = self.work_please(request)
  932. i = 1
  933. form = get_rate(request.POST)
  934. for check in checks:
  935. current_profile = check.checker
  936. profile = Profile.objects.get(user=current_profile)
  937. if form.is_valid():
  938. if request.method == 'POST' and f'btn{i}' in request.POST:
  939. new_rating = Rating_checker()
  940. new_rating.user = current_profile
  941. new_rating.checker_rating = form.cleaned_data.get("checker_rating")
  942. new_rating.rating_of_rater = Profile.objects.get(user=request.user).rating
  943. new_rating.number = i
  944. new_rating.save()
  945.  
  946. # Оценка умножается на рейтинг оценивающего и количество оценок увеличивается на рейтинг, а не
  947. # просто количество! Так что тут всё нормально, гуляй
  948. checker_rating = Rating_checker.objects.filter(user=current_profile)
  949. c_sum = 0
  950. num_of_checks = 0
  951. for c_rate in checker_rating:
  952. c_sum += c_rate.checker_rating * ((c_rate.rating_of_rater ** 2) / 50 + 1)
  953. num_of_checks += ((c_rate.rating_of_rater ** 2) / 50 + 1)
  954. average_checker_rating = c_sum / num_of_checks
  955. profile.checker_rating = average_checker_rating
  956.  
  957. average_essay_rating = profile.essay_rating
  958.  
  959. # Подсчёт и запись итогового рейтинга
  960. final_score = (1.2 * profile.checker_rating + 0.8 * average_essay_rating) / 2
  961.  
  962. if final_score > profile.rating / 2:
  963. profile.rating += round(0.15 * (final_score - profile.rating / 2), 2)
  964. else:
  965. profile.rating -= round(0.15 * (profile.rating / 2 - final_score), 2)
  966. if profile.rating > 10:
  967. profile.rating = 10
  968. if profile.rating < 0:
  969. profile.rating = 0
  970. profile.save()
  971.  
  972. return HttpResponseRedirect('/look')
  973. i += 1
  974.  
  975. essay_parts = essay.Body.split('\n')
  976. essay_parts = [x for x in essay_parts if x not in [None, '\n', '\r', '']]
  977.  
  978. data = {
  979. 'form': form,
  980. 'profile': profile,
  981. 'essay': essay,
  982. 'checks': checks,
  983. 'which_step_title': which_step_title,
  984. 'essay_parts': essay_parts,
  985. }
  986. return render(request, 'look.html', data)
  987.  
  988.  
  989. class Test(View):
  990. # Требуется авторизация, чтобы фукнция внутри класса запустилась
  991. @method_decorator(login_required)
  992. def get(self, request):
  993. logger.info(f': {request.user} открыта страница /test')
  994. profile = Profile.objects.get(user=request.user)
  995. get_user_profile_avatars(profile, request)
  996. if profile.ban == 0:
  997. form = get_answer
  998. test_questions = Test_question.objects.all()
  999. num_of_questions = test_questions.count()
  1000.  
  1001. # txt_generate = ''
  1002. # for i in test_questions.all():
  1003. # txt_generate += '№' + str(i.number) + '\n'
  1004. # txt_generate += i.question + '\n'
  1005. # txt_generate += i.answer_1 + '\n'
  1006. # txt_generate += i.answer_2 + '\n'
  1007. # txt_generate += i.answer_3 + '\n'
  1008. # txt_generate += i.answer_4 + '\n'
  1009. # txt_generate += i.answer_5 + '\n'
  1010. # txt_generate += "ответ: " + i.right_answer + '\n'
  1011. # txt_generate += "\n-----------\n"
  1012. #
  1013. # with open("backup_questions.txt", "w") as text_file:
  1014. # text_file.write(txt_generate)
  1015.  
  1016. if not Questions_list.objects.filter(user=request.user).exists():
  1017. new_question_list = Questions_list()
  1018. new_question_list.user = request.user
  1019. new_question_list.save()
  1020. i = 1
  1021. while i < 11:
  1022. random_question = test_questions.get(number=random.randint(1, num_of_questions))
  1023. if random_question not in new_question_list.question.all():
  1024. new_question_list.question.add(random_question)
  1025. new_question_list.number = i
  1026. new_question_list.save()
  1027. i += 1
  1028.  
  1029. # Проверка, дан ли ответ на вопрос
  1030. questions_list = Questions_list.objects.get(user=request.user)
  1031. answered_questions_numbers = []
  1032. for question in questions_list.question.all():
  1033. if Answer.objects.filter(user=request.user, question=question).exists():
  1034. answered_questions_numbers.append(question.number)
  1035.  
  1036. data = {
  1037. 'form': form,
  1038. 'questions': Questions_list.objects.get(user=request.user),
  1039. 'which_step_title': "обязательное тестирование",
  1040. 'profile': Profile.objects.get(user=request.user),
  1041. 'user': request.user,
  1042. 'answered_questions_numbers': answered_questions_numbers,
  1043. }
  1044.  
  1045. count_user_answers = Answer.objects.filter(user=request.user).count()
  1046. if count_user_answers > 9:
  1047. data['is_test_passed'] = True
  1048.  
  1049. mark = 0
  1050. for answer in Answer.objects.filter(user=request.user):
  1051. right_answer = Test_question.objects.get(question=answer.question).right_answer
  1052. if answer.answer == right_answer:
  1053. mark += 1
  1054. data['number_of_correct_answers'] = mark
  1055.  
  1056. return render(request, 'test.html', data)
  1057. else:
  1058. return redirect('/')
  1059.  
  1060. def post(self, request):
  1061. form = get_answer(request.POST)
  1062. questions_list = Questions_list.objects.get(user=request.user)
  1063. i = 0
  1064. for question in questions_list.question.all():
  1065. i += 1
  1066. if form.is_valid():
  1067. double_send = Answer.objects.filter(question=Test_question.objects.get(number=question.number)).exists()
  1068. if request.method == 'POST' and f'btn{i}' in request.POST and not double_send:
  1069. new_answer = Answer()
  1070. new_answer.user = request.user
  1071. new_answer.question = Test_question.objects.get(number=question.number)
  1072. new_answer.answer = form.cleaned_data.get("answer")
  1073. new_answer.save() # Продолжаем
  1074. count_user_answers = Answer.objects.filter(user=request.user).count()
  1075. if count_user_answers == 10:
  1076. logger.info(f': {request.user} ответил на все вопросы на странице /test')
  1077. mark = 0
  1078. for answer in Answer.objects.filter(user=request.user):
  1079. right_answer = Test_question.objects.get(question=answer.question).right_answer
  1080. if answer.answer == right_answer:
  1081. mark += 1
  1082. profile = Profile.objects.get(user=request.user)
  1083. profile.rating = 0.3 * mark
  1084. profile.save()
  1085.  
  1086. logger.info(f': {request.user} отправил {count_user_answers} форму на страцине /test')
  1087. if request.method == 'POST' and f'btn{i}' in request.POST:
  1088. return redirect('/test')
  1089.  
  1090.  
  1091. def generate_soch_backup():
  1092. text = Text.objects.order_by('-id')[0:1].get()
  1093. text_parts = text.Body.split('\n')
  1094. text_parts = '<p class="main_text">'.join(x + '</p>' for x in text_parts if x not in [None, '\n', '\r', ''])
  1095.  
  1096. text_author = text.Author
  1097. text_author_description = text.Author_description
  1098.  
  1099. week_number = text.week_number
  1100. html_generate = f"""<div class="main_content">
  1101. <h2 class="tri_prov">3Проверочки</h2>
  1102. <h4 class="tri_prov">Неделя {week_number}</h4>
  1103. <div class="text"><p class="main_text">{text_parts}
  1104. <p class="author_info_name">{text_author}</p>
  1105. <p>{text_author_description}</p></div>
  1106. <p style="page-break-before: always" ></p>"""
  1107.  
  1108.  
  1109. path_to_save = f"{BASE_DIR}/work_outputs/week_{week_number}/сочинения"
  1110. os.makedirs(path_to_save, exist_ok=True)
  1111.  
  1112. all_week_soch = Essay.objects.filter(text=text)
  1113. for soch in all_week_soch:
  1114. soch_author = soch.user
  1115.  
  1116. _soch_Body = soch.Body.split('\n')
  1117. soch_parts = '<p class="soch_text">'.join(x + '</p>' for x in _soch_Body if x not in [None, '\n', '\r', ''])
  1118.  
  1119. soch_parts = '<p class="soch_text">' + soch_parts
  1120.  
  1121. soch_pass_time = soch.time
  1122.  
  1123. html_generate += f"""<h5 class="what_is_it">Сочинение</h5><div class="soch">{soch_parts}</div>"""
  1124. html_generate += f"""<div class="author">
  1125. <li>Автор сочинения: {soch_author.first_name} {soch_author.last_name} ({soch_author})</li>
  1126. <li>Дата отправки: {datetime.strftime(soch_pass_time, '%d.%m.%Y %H:%M:%S')}</li></div>"""
  1127.  
  1128. html_generate += my_config.html_generate_css
  1129.  
  1130. # html = HTML(string=html_generate)
  1131. # html.write_pdf(f'{BASE_DIR}/example_{soch_author}.pdf')
  1132.  
  1133.  
  1134. with open(f"{path_to_save}/soch_{soch_author}.html", "w") as text_file:
  1135. text_file.write(html_generate)
  1136. # weasyprint here
  1137.  
  1138. html_generate = f"""<div class="main_content">
  1139. <h2 class="tri_prov">3Проверочки</h2>
  1140. <h4 class="tri_prov">Неделя {week_number}</h4>
  1141. <div class="text"><p class="main_text">{text_parts}
  1142. <p class="author_info_name">{text_author}</p>
  1143. <p>{text_author_description}</p></div>
  1144. <p style="page-break-before: always" ></p>"""
  1145.  
  1146.  
  1147. def generate_checks_backup():
  1148. text = Text.objects.order_by('-id')[0:1].get()
  1149. text_parts = text.Body.split('\n')
  1150. text_parts = '<p class="main_text">'.join(x + '</p>' for x in text_parts if x not in [None, '\n', '\r', ''])
  1151.  
  1152. text_author = text.Author
  1153. text_author_description = text.Author_description
  1154.  
  1155. week_number = text.week_number
  1156. html_generate = f"""<div class="main_content">
  1157. <h2 class="tri_prov">3Проверочки</h2>
  1158. <h4 class="tri_prov">Неделя {week_number}</h4>
  1159. <div class="text"><p class="main_text">{text_parts}
  1160. <p class="author_info_name">{text_author}</p>
  1161. <p>{text_author_description}</p></div>
  1162. <p style="page-break-before: always" ></p>"""
  1163.  
  1164. path_to_save = f"{BASE_DIR}/work_outputs/week_{week_number}/проверки"
  1165. os.makedirs(path_to_save, exist_ok=True)
  1166.  
  1167. all_week_checks = Check_Result.objects.filter(Text=text)
  1168. for check in all_week_checks:
  1169. _essay = check.essay.Body.split('\n')
  1170. soch_parts = '<p class="soch_text">'.join(x + '</p>' for x in _essay if x not in [None, '\n', '\r', ''])
  1171. soch_parts = '<p class="soch_text">' + soch_parts
  1172. html_generate += f"""<h5 class="what_is_it">Сочинение</h5><div class="soch">{soch_parts}</div>"""
  1173.  
  1174. html_generate += """<p style="page-break-before: always" ></p>"""
  1175.  
  1176. html_generate += """<h5 class="what_is_it">Проверка</h5>"""
  1177. html_generate += f"""<div class="check">{check.summernote_editor}</div>"""
  1178. html_generate += f"""<div class="author">
  1179. <li>Автор проверки: {check.checker.first_name} {check.checker.last_name} ({check.checker})</li>"""
  1180.  
  1181. html_generate += """<div class="table">"""
  1182.  
  1183. # чел, удачи сделать по-другому
  1184. html_generate += f"""<li>К1 - {check.k1} {check.k1_comment}</li>"""
  1185. html_generate += f"""<li>К2 - {check.k2} {check.k2_comment}</li>"""
  1186. html_generate += f"""<li>К3 - {check.k3} {check.k3_comment}</li>"""
  1187. html_generate += f"""<li>К4 - {check.k4} {check.k4_comment}</li>"""
  1188. html_generate += f"""<li>К5 - {check.k5} {check.k5_comment}</li>"""
  1189. html_generate += f"""<li>К6 - {check.k6} {check.k6_comment}</li>"""
  1190. html_generate += f"""<li>К7 - {check.k7} {check.k7_comment}</li>"""
  1191. html_generate += f"""<li>К8 - {check.k8} {check.k8_comment}</li>"""
  1192. html_generate += f"""<li>К9 - {check.k9} {check.k9_comment}</li>"""
  1193. html_generate += f"""<li>К10 - {check.k10} {check.k10_comment}</li>"""
  1194. html_generate += f"""<li>К11 - {check.k11} {check.k11_comment}</li>"""
  1195. html_generate += f"""<li>К12 - {check.k12} {check.k12_comment}</li></div>"""
  1196.  
  1197. html_generate += f"""<li>Итого: {check.score} баллов</li></div>"""
  1198.  
  1199. html_generate += my_config.html_generate_css
  1200.  
  1201. with open(f"{path_to_save}/check_{check.checker}_{check.essay.user}.html", "w") as text_file:
  1202. text_file.write(html_generate)
  1203. # weasyprint here
  1204.  
  1205. html_generate = f"""<div class="main_content">
  1206. <h2 class="tri_prov">3Проверочки</h2>
  1207. <h4 class="tri_prov">Неделя {week_number}</h4>
  1208. <div class="text"><p class="main_text">{text_parts}
  1209. <p class="author_info_name">{text_author}</p>
  1210. <p>{text_author_description}</p></div>
  1211. <p style="page-break-before: always" ></p>"""
  1212.  
  1213.  
  1214. def turner(request):
  1215. if request.user.is_superuser:
  1216. what_time = RUBILNIK.objects.all().order_by('-id').get()
  1217. profile = Profile.objects.all()
  1218. text = Text.objects.order_by('-id')[0:1].get()
  1219. text.Number_of_essays = Essay.objects.filter(text=text).count()
  1220. if what_time.sent_check == 0:
  1221. # смена на этап сдачи сочинений
  1222. what_time.sent_check = 1
  1223. new_bad_user = Bad_user()
  1224. new_bad_user.save()
  1225. bad_user = Bad_user.objects.order_by('-id')[0:1].get()
  1226. for _ in profile:
  1227. # Список даунов, не проверивших все сочины...
  1228. for is_bad_user in profile:
  1229. if is_bad_user.check_number < 3:
  1230. print('> ', is_bad_user.user)
  1231. print('>>> ', is_bad_user.check_number)
  1232. bad_user.user.add(is_bad_user.user)
  1233. Essays_list.objects.all().delete()
  1234. Questions_list.objects.all().delete()
  1235. Answer.objects.all().delete()
  1236. logger.info(f'{request.user} поменял на этап сдачи сочинений')
  1237.  
  1238. logger.info('Бэкап проверок...')
  1239. generate_checks_backup()
  1240.  
  1241. else:
  1242. # смена на этап сдачи проверок
  1243. what_time.sent_check = 0
  1244. Answer.objects.all().delete()
  1245. Questions_list.objects.all().delete()
  1246. logger.info(f'{request.user} поменял на этап сдачи проверок')
  1247.  
  1248. logger.info('Бэкап сочинений...')
  1249. generate_soch_backup()
  1250.  
  1251. what_time.save()
  1252. return redirect("/profile/#tab_1")
  1253. else:
  1254. return redirect('/')
  1255.  
  1256.  
  1257. def error_404(request, exception):
  1258. which_step_title = 'ошибка!'
  1259. logger.error(f': {request.user} ошибка error_404 -> {exception}')
  1260.  
  1261. data = {
  1262. 'which_step_title': which_step_title,
  1263. 'profile': profile,
  1264. }
  1265.  
  1266. return render(request, 'error_pages/error_page_404.html', data)
  1267.  
  1268.  
  1269. def error_500(request):
  1270. which_step_title = 'ошибка!'
  1271. logger.error(f': {request.user} ошибка error_500')
  1272.  
  1273. data = {
  1274. 'which_step_title': which_step_title,
  1275. 'profile': profile,
  1276. }
  1277.  
  1278. return render(request, 'error_pages/error_page_500.html', data)
  1279.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement