def view_thread(request): if request.method == 'POST': form = Post_Form() file_form = UploadFileForm(request.FILES) #Парсим из текста сообщения номера постов, на которые в нём есть ответ. temp = pars_for_answer(request.POST.get('text_input')) post = Anon_Post.objects.create(post_text = pars_for_anchor(request.POST.get('text_input')), post_pict = request.FILES.get('files'), post_time = datetime.now(), post_email = request.POST.get('email_input') ) #Каждому посту из текста добавляем атрибут с номером поста, который на него ответил. for element in temp: temp_post = Anon_Post.objects.get(id = int(element)) temp_post.post_answer = temp_post.post_answer + " " + ("<a href=\"#%s\">>>%s</a>" % (post.id, post.id)) temp_post.save() else: form = Post_Form() file_form = UploadFileForm() return render(request,'imageboard_app/thread.html', {'form':form, 'posts':Anon_Post.objects.all(), 'file_form':file_form, })
def view_b(request): if request.method == 'POST': create_thread_form = Post_Form() upload_file_form = UploadFileForm(request.FILES) #Парсим из текста сообщения номера постов, на которые в нём есть ответ. temp = pars_for_answer(request.POST.get('text_input')) thread = Thread.objects.create(thread_message = pars_for_anchor(request.POST.get('text_input')), thread_pict = request.FILES.get('files'), thread_time = datetime.now(), thread_email = request.POST.get('email_input'), thread_theme = request.POST.get('theme_input'), ) else: create_thread_form = Post_Form() upload_file_form = UploadFileForm() return render(request,'imageboard_app/b.html', {'create_thread_form':create_thread_form, 'threads':Thread.objects.all(), 'upload_file_form':upload_file_form, })
def view_section(request, section_name): # Получение трёх последних постов треда. @register.filter def filter_f(post_list, counter): return post_list[counter][::-1] # Проверка существования запрошенного раздела. if Section.objects.filter(section_name = section_name).exists(): # Получаем список всех тредов в разделе. # А так же три последних поста в каждом из тредов. thread_list, thread_three_posts = thread_list_f(section_name) # Получаем все посты в выбранном разделе. posts_in_section = Anon_Post.objects.filter( post_section = section_name) if request.method == 'POST': # Получаем номер, который будет присвоен треду после создания thread_id_section = pub_thread_number( section_name, posts_in_section) # Создаём формы для постинга и загрузки файла. create_thread_form = Post_Form(request.POST) upload_file_form = UploadFileForm(request.POST,request.FILES) # При условии валидности как текста сообщения, так и наличия картинки... if upload_file_form.is_valid(): if create_thread_form.is_valid(): #Создаём и сохраняем превью картинки на диск. create_preview(request.FILES.get('files')) #И создаём запись треда в базе данных. thread = Thread.objects.create( #Функция pars_for_anchor заменяет сообщения вида ">>2" на ссылки-якоря. thread_message = pars_for_anchor( request.POST.get('text_input'), section_name, thread_id_section), thread_pict = request.FILES.get('files'), # Забираем превьюшку с диска. Создание превьюшки с именем, начинающимся с # small_ намертво зашито в функцию create_preview thread_pict_small = ('small_%s' % (request.FILES.get('files').name)), thread_time = datetime.now(), thread_email = request.POST.get('email_input'), thread_theme = request.POST.get('theme_input'), thread_section = section_name, thread_id_section = thread_id_section, ) return HttpResponseRedirect('/%s/' % (section_name)) else: create_thread_form = Post_Form() upload_file_form = UploadFileForm() # Возвращаем для рендеринга страницы много всего. return render(request,'imageboard_app/section.html', { 'create_thread_form':create_thread_form, 'upload_file_form':upload_file_form, 'threads': thread_list, 'section_name':section_name, 'posts_in_section':posts_in_section, 'section_visible_name':Section.objects.get( section_name = section_name).section_visible_name, 'thread_three_posts': thread_three_posts, }) # Если мы не нашли раздел, то возвращаем заглушку. else: return HttpResponseNotFound\ ('<h1 align = "center">Section not found 404</h1>')
def view_thread(request, section_name, thread_id_section): # Получаем тред thread = Thread.objects.get( thread_section = section_name, thread_id_section = thread_id_section, ) # Получаем объекты раздела (в каком разделе мы находимся?) object_section = Section.objects.get(section_name = section_name) # Создаём классы FormsetFactory, т.к. в треде более 1 одинаковой формы. # Используя наши классы-модели. Минимальная валидация, т.к. есть необязатель # ные поля. PostFormSet = formset_factory( Post_Form, extra=1, min_num=1, validate_min=True,) FileFormSet = formset_factory( UploadFileForm, extra=1, min_num=2, validate_min=True,) if request.method == 'POST': # Создаём объекты-formset. post_formset = PostFormSet(request.POST) file_formset = FileFormSet(request.POST, request.FILES) # Узнаём, какой номер поста нужно присвоить новому посту. post_id_section = pub_thread_number( section_name, Anon_Post.objects.filter(post_section = section_name)) # Если валидна верхняя форма для постинга, то работаем с ней. # Объявляем в form_num, что надо работать c данными из верхней формы. if post_formset[0].is_valid() or file_formset[0].is_valid(): form_num = 'form-0' # Ну, если валидна нижняя, то работаем уже с ней. # И да, странная проблема, валидна она всегда. elif post_formset[1].is_valid() or file_formset[1].is_valid(): form_num = 'form-1' # Проверяем, есть ли у нас картинка или сообщение. Дополнительные проверка # идёт из-за странного поведения form-1 -она всегда валидна. if (bool(request.POST.get('%s-text_input' % (form_num))) or bool(request.FILES.get('%s-files' % (form_num)))): post = Anon_Post.objects.create( post_text = pars_for_anchor( request.POST.get('%s-text_input' % (form_num)), section_name, thread_id_section), post_pict = ( request.FILES.get('%s-files' % (form_num)) or None), post_time = datetime.now(), post_email = request.POST.get('%s-email_input' % (form_num)), post_thread = thread, post_section = section_name, post_id_section = post_id_section, ) # При условии наличия картинки мы создаём превьюшку. if post.post_pict: path = (os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/imageboard_app/media/%s" % (post.post_pict.name[2:]) ) create_preview(link = path, name = post.post_pict.name[2:]) post.post_pict_small = 'small_%s' % (post.post_pict.name[2:]) post.save() # Если в постe обнаружен текст вида ">>3", # то добавляем обьекту, на который ссылается пост, значение, # в специальный атрибут, со всеми ссылающимися на него постами. post_answer_f( pars_for_answer( request.POST.get('%s-text_input' % (form_num))), thread, section_name, post_id_section) # Обновляем значение thread_updated (оно используется для сортировки тредов) # при выводе их в разделе. thread.thread_updated = datetime.now() # Тут проверяем количество постов в треде, # наличие картинок в ответах. # Используется для вывода подписи "пропущено столько-то постов" под тредом. if thread.posts.all().count() > 3: thread.thread_s_answer_count += 1 if post.post_pict: thread.thread_p_answer_count += 1 thread.save() return HttpResponseRedirect( '/%s/%s/' % (section_name, thread_id_section) ) else: post_formset = PostFormSet() file_formset = FileFormSet() return render(request,'imageboard_app/thread.html', { 'form':post_formset, 'posts':Anon_Post.objects.filter(post_thread=thread.id), 'file_form':file_formset, 'thread_id_section': thread_id_section, 'thread':thread, 'section_name':thread.thread_section, 'section_visible_name':object_section.section_visible_name, })