def thread(request, thread): """ 增加帖子子的点击数 并显示本帖子里发布的话题 """ try: t = Thread.objects.select_related().get(pk=thread) if not Forum.objects.has_access(t.forum, request.user.groups.all()): raise Http404 except Thread.DoesNotExist: raise Http404 p = t.post_set.select_related('author').all().order_by('time') # 增加帖子的访问量 t.views += 1 t.save() form = ReplyForm() return object_list(request, queryset=p, paginate_by=FORUM_PER_PAGE, template_object_name='post', template_name='forum/thread.html', extra_context={ 'forum': t.forum, 'thread': t, 'form': form, })
def get_context_data(self, **kwargs): context = super(ThreadView, self).get_context_data(**kwargs) self.subscribe = None if self.request.user.is_authenticated(): self.subscribe = self.thread.subscription_set.select_related( ).filter(author=self.request.user) if self.subscribe: initial = {'subscribe': True} else: initial = {'subscribe': False} form = ReplyForm(initial=initial) extra_context = { 'forum': self.forum, 'thread': self.thread, 'object': self.thread, 'subscription': self.subscribe, 'form': form, } context.update(extra_context) return context
def post_reply(request, topic_id): form = ReplyForm() topic = Topic.objects.get(pk=topic_id) if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = Post() post.topic = topic #post.title = form.cleaned_data['title'] post.body = form.cleaned_data['body'] post.creator = request.user post.user_ip = request.META['REMOTE_ADDR'] post.save() return HttpResponseRedirect( reverse('forum:topic-detail', args=(topic.id, ))) return render(request, 'forum/reply.html', { 'form': form, 'topic': topic, })
def get_context_data(self, **kwargs): data = super(TopicView, self).get_context_data(**kwargs) topic_id = self.kwargs['topic_id'] topic = get_object_or_404(Topic, id=topic_id) data['topic'] = topic topic.viewed += 1 topic.save() replies = topic.replies.all() paginator = Paginator(replies, 10) page = self.request.GET.get('page') try: reply_list = paginator.page(page) except PageNotAnInteger: reply_list = paginator.page(paginator.num_pages) except EmptyPage: reply_list = paginator.page(paginator.num_pages) page_list = get_pagination(reply_list.number, paginator.num_pages, 2) ilike = False if self.request.user.is_authenticated(): ilike = self.request.user.like_topics.filter(id=topic_id).exists() data['replies'] = reply_list data['page_list'] = page_list data['form'] = ReplyForm() data['ilike'] = ilike return data
def get_context_data(self, **kwargs): context = super(TopicDetailView, self).get_context_data(**kwargs) if self.request.user.is_authenticated(): context['form'] = ReplyForm() context['object'] = self.object return context
def post(self, request, *args, **kwargs): topic_id = self.kwargs['topic_id'] topic = get_object_or_404(Topic, id=topic_id) form = ReplyForm(self.request.POST) if form.is_valid(): md = form.cleaned_data['content'] rendered = render_markdown(md) reply = Reply(topic=topic, author=request.user, markdown=md, content=rendered) mentioned = get_metioned_user(request.user, md) self._commit_changes(topic, reply, mentioned) return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': topic_id}))
def thread(request, thread): """View a thread. Increments the viewed count on a thread then displays the posts for that thread, in chronological order. @param thread: thread id to work on @type thread: integer @return a thread's view @rtype: Django object_list @raise Http404: if thread doesn't exist """ try: t = Thread.objects.select_related().get(pk=thread) if not Forum.objects.has_access(t.forum, request.user.groups.all()): return HttpResponseForbidden() except Thread.DoesNotExist: raise Http404 p = t.post_set.select_related('author').all().order_by('time') s = None if request.user.is_authenticated(): s = t.subscription_set.select_related().filter(author=request.user) t.views += 1 t.save() if s: initial = {'subscribe': True} else: initial = {'subscribe': False} form = ReplyForm(initial=initial) return object_list(request, queryset=p, paginate_by=FORUM_PAGINATION, template_object_name='post', template_name='forum/thread.html', extra_context={ 'forum': t.forum, 'thread': t, 'subscription': s, 'form': form, 'login': { 'reason': _('post a reply'), 'next': t.get_absolute_url(), }, 'section': 'forum', })
def reply(request, thread): """ 回复帖子子 条件: 1、帖子允许回复,没有关闭 2、当前用户登录 """ t = get_object_or_404(Thread, pk=thread) if t.closed: return Http404 if not Forum.objects.has_access(t.forum, request.user.groups.all()): return Http404 if request.method == "POST": form = ReplyForm(request.POST) if form.is_valid(): body = form.cleaned_data['body'] p = Post( thread=t, author=request.user, body=body, time=datetime.now(), ) p.save() return HttpResponseRedirect(p.get_absolute_url()) else: form = ReplyForm() return render_to_response( 'forum/reply.html', RequestContext(request, { 'form': form, 'forum': t.forum, 'thread': t, }))
def thread(request, thread, flag_partner=False): """ Increments the viewed count on a thread then displays the posts for that thread, in chronological order. """ try: t = Thread.objects.select_related().get(pk=thread, forum__for_partner=flag_partner) if t.forum.for_partner: if request.user.is_authenticated() and request.user.get_profile().is_partner():pass else: messages.add_message(request, messages.ERROR, 'Пожалуйста, авторизируйтесь как партнер.') return redirect('/accounts/login/?next=%s' % request.path) if not Forum.objects.has_access(t.forum, request.user.groups.all()): raise Http404 except Thread.DoesNotExist: raise Http404 p = t.post_set.select_related('author').all().order_by('time') s = None if request.user.is_authenticated(): s = t.subscription_set.select_related().filter(author=request.user) t.views += 1 t.save() if s: initial = {'subscribe': True} else: initial = {'subscribe': False} form = ReplyForm(initial=initial) formset = AttachFileFormset() return object_list( request, queryset=p, paginate_by=FORUM_PAGINATION, template_object_name='post', template_name='forum/thread.html', extra_context = { 'forum': t.forum, 'thread': t, 'subscription': s, 'form': form, 'formset': formset, 'flag_partner':flag_partner } )
def post(self, request, *args, **kwargs): if not self.request.user.is_authenticated: messages.warning( self.request, 'Para responde ao tópico é necessário esta logado') return redirect(self.request.path) self.object = self.get_object() context = self.get_context_data(object=self.object) form = context['form'] if form.is_valid(): # save(commit=Não salva o formulário no banco apenas preche os campos no form.) reply = form.save(commit=False) reply.thread = self.object reply.author = self.request.user reply.save() messages.success( self.request, 'A sua resposta foi enviada com sucesso' ) context['form'] = ReplyForm() return self.render_to_response(context)
def thread(request, thread): """ Increments the viewed count on a thread then displays the posts for that thread, in chronological order. """ try: t = Thread.objects.select_related().get(pk=thread) if not Forum.objects.has_access(t.forum, request.user.groups.all()): raise Http404 except Thread.DoesNotExist: raise Http404 p = t.post_set.select_related('author').all().order_by('time') s = None if request.user.is_authenticated(): s = t.subscription_set.select_related().filter(author=request.user) t.views += 1 t.save() if s: initial = {'subscribe': True} else: initial = {'subscribe': False} form = ReplyForm(initial=initial) formset = AttachFileFormset() return object_list(request, queryset=p, paginate_by=FORUM_PAGINATION, template_object_name='post', template_name='forum/thread.html', extra_context={ 'forum': t.forum, 'thread': t, 'subscription': s, 'form': form, 'formset': formset, 'active': 7, })
def reply(request, thread): """ If a thread isn't closed, and the user is logged in, post a reply to a thread. Note we don't have "nested" replies at this stage. """ if not request.user.is_authenticated(): return HttpResponseServerError() t = get_object_or_404(Thread, pk=thread) if t.closed: return HttpResponseServerError() if not Forum.objects.has_access(t.forum, request.user.groups.all()): return HttpResponseForbidden() if request.method == "POST": form = ReplyForm(data=request.POST, files=request.FILES) if form.is_valid(): body = form.cleaned_data['body'] p = Post( thread=t, author=request.user, body=body, time=datetime.now(), ) p.save() sub = Subscription.objects.filter(thread=t, author=request.user) if form.cleaned_data.get('subscribe',False): if not sub: s = Subscription( author=request.user, thread=t ) s.save() else: if sub: sub.delete() # Subscriptions are updated now send mail to all the authors subscribed in # this thread. mail_subject = '' try: mail_subject = settings.FORUM_MAIL_PREFIX except AttributeError: mail_subject = '[Forum]' mail_from = '' try: mail_from = settings.FORUM_MAIL_FROM except AttributeError: mail_from = settings.DEFAULT_FROM_EMAIL mail_tpl = loader.get_template('forum/notify.txt') c = Context({ 'body': wordwrap(striptags(body), 72), 'site' : Site.objects.get_current(), 'thread': t, }) email = EmailMessage( subject=mail_subject+' '+striptags(t.title), body= mail_tpl.render(c), from_email=mail_from, to=[mail_from], bcc=[s.author.email for s in t.subscription_set.all()],) email.send(fail_silently=True) ## data={'title': t.title, ## 'summary': t.title, ## 'attached_timestamp':datetime.now() ## } ## attachment_form=AttachmentForm(data=data,files=form.files) ## a=attachment_form.errors ## content_type =ContentType.objects.get_for_model(Post) ## object_id = p.id ## ffs=form.files ## debug() ## if attachment_form.is_valid(): ## attachment = attachment_form.save(commit=False) ## attachment.content_type = content_type ## attachment.object_id = object_id ## attachment.attached_by = request.user ## attachment.save() # for attachedfilefield in form.files: # #file_path = '%s%s' % (settings.MEDIA_ROOT, form.files[attachedfilefield]) # attachment_file = form.files[attachedfilefield] # file_path =os.path.join(ATTACHMENT_DIR, randomfilename(attachment_file.name)) # (mimetype, encoding) = mimetypes.guess_type(file_path) # # try: # mime_type = mimetype # except: # mime_type = 'text/plain' # # attach=Attachment( # content_type =ContentType.objects.get_for_model(Post), # object_id = p.id, # title = attachment_file.name, # summary = t.title, # attached_by = request.user, # ) # attach.save_uploaded_file(attachment_file) # attach.save() for attachedfilefield in form.files: #file_path = '%s%s' % (settings.MEDIA_ROOT, form.files[attachedfilefield]) attachment_file = form.files[attachedfilefield] attach=Attachment() attach.handle_uploaded_attachment(p, attachment_file, request.user, attachment_file.name, t.title ) return HttpResponseRedirect(p.get_absolute_url()) else: form = ReplyForm() return render_to_response('forum/reply.html', RequestContext(request, { 'form': form, 'forum': t.forum, 'thread': t, }))
def reply(request, thread, flag_partner=False): """ If a thread isn't closed, and the user is logged in, post a reply to a thread. Note we don't have "nested" replies at this stage. """ if flag_partner: if request.user.is_authenticated() and request.user.get_profile().is_partner():pass else: messages.add_message(request, messages.ERROR, 'Пожалуйста, авторизируйтесь как партнер.') return redirect('/accounts/login/?next=%s' % request.path) if not request.user.is_authenticated(): return HttpResponseRedirect('%s?next=%s' % (LOGIN_URL, request.path)) t = get_object_or_404(Thread, pk=thread) if t.closed: return HttpResponseServerError() if not Forum.objects.has_access(t.forum, request.user.groups.all()): return HttpResponseForbidden() if request.method == "POST": form = ReplyForm(request.POST) formset = AttachFileFormset(request.POST, request.FILES) if form.is_valid() and formset.is_valid(): p = Post( thread=t, author=request.user, body=form.cleaned_data['body'], time=datetime.now(), ) p.save() formset.instance = p formset.save() sub = Subscription.objects.filter(thread=t, author=request.user) if form.cleaned_data.get('subscribe',False): if not sub: s = Subscription(author=request.user, thread=t) s.save() else: if sub: sub.delete() if t.subscription_set.count() > 0: mail_subject = '' try: mail_subject = settings.FORUM_MAIL_PREFIX except AttributeError: mail_subject = '[Forum]' mail_from = '' try: mail_from = settings.FORUM_MAIL_FROM except AttributeError: mail_from = settings.DEFAULT_FROM_EMAIL mail_tpl = loader.get_template('forum/notify.txt') body = form.cleaned_data['body'] c = Context({ 'body': wordwrap(striptags(body), 72), 'site' : Site.objects.get_current(), 'thread': t, }) email = EmailMessage( subject=mail_subject+' '+striptags(t.title), body= mail_tpl.render(c), from_email=mail_from, bcc=[s.author.email for s in t.subscription_set.all()],) email.send(fail_silently=True) return HttpResponseRedirect(p.get_absolute_url()) else: form = ReplyForm() formset = AttachFileFormset() return render_to_response('forum/reply.html', RequestContext(request, { 'form': form, 'formset': formset, 'forum': t.forum, 'thread': t, 'flag_partner':flag_partner }))
def thread(request, thread): """ Increments the viewed count on a thread then displays the posts for that thread, in chronological order. """ t = get_object_or_404(Thread, pk=thread) p = t.post_set.all().order_by('time') if request.user.is_authenticated(): s = t.subscription_set.filter(author=request.user) else: s = False # If the user is not authorized to view, we redirect them if t.forum.is_private and request.user.is_staff != True: return HttpResponseRedirect('/forum') # Process reply form if it was sent if (request.method == 'POST'): if not request.user.is_authenticated() or t.closed: return HttpResponseServerError() reply_form = ReplyForm(request.POST) if reply_form.is_valid(): new_post = reply_form.save(commit=False) new_post.author = request.user new_post.thread = t new_post.time = datetime.now() new_post.save() # Change subscription if reply_form.cleaned_data['subscribe']: Subscription.objects.get_or_create(thread=t, author=request.user) else: Subscription.objects.filter(thread=t, author=request.user).delete() # Send email forum_email_notification(new_post) return HttpResponseRedirect(new_post.get_absolute_url()) else: reply_form = ReplyForm(initial={'subscribe': s}) # Pagination paginator = Paginator(p, settings.FORUM_PAGINATE) try: page = int(request.GET.get('page', paginator.num_pages)) except: page = paginator.num_pages try: posts = paginator.page(page) except (EmptyPage, InvalidPage): posts = paginator.page(paginator.num_pages) t.views += 1 t.save() #{'object_list' : artistic.object_list, 'page_range' : paginator.page_range, 'page' : page, 'letter' : letter, 'al': alphalist}, \ return j2shim.r2r( 'forum/thread.html', { 'forum': t.forum, 'thread': t, 'posts': posts.object_list, 'page_range': paginator.page_range, 'page': page, 'reply_form': reply_form }, request)
def get_context_data(self, **kwargs): context = super(ThreadView, self).get_context_data(**kwargs) context['tags'] = Thread.tags.all() context['form'] = ReplyForm(self.request.POST or None) return context
def reply(request, thread): """ If a thread isn't closed, and the user is logged in, post a reply to a thread. Note we don't have "nested" replies at this stage. """ if not request.user.is_authenticated(): return HttpResponseRedirect('%s?next=%s' % (LOGIN_URL, request.path)) t = get_object_or_404(Thread, pk=thread) if t.closed: return HttpResponseServerError() if not Forum.objects.has_access(t.forum, request.user.groups.all()): return HttpResponseForbidden() if request.method == "POST": form = ReplyForm(request.POST) if form.is_valid(): body = form.cleaned_data['body'] p = Post( thread=t, author=request.user, body=body, time=datetime.now(), ) p.save() sub = Subscription.objects.filter(thread=t, author=request.user) if form.cleaned_data.get('subscribe', False): if not sub: s = Subscription(author=request.user, thread=t) s.save() else: if sub: sub.delete() if t.subscription_set.count() > 0: # Subscriptions are updated now send mail to all the authors subscribed in # this thread. mail_subject = '' try: mail_subject = settings.FORUM_MAIL_PREFIX except AttributeError: mail_subject = '[Forum]' mail_from = '' try: mail_from = settings.FORUM_MAIL_FROM except AttributeError: mail_from = settings.DEFAULT_FROM_EMAIL mail_tpl = loader.get_template('forum/notify.txt') c = Context({ 'body': wordwrap(striptags(body), 72), 'site': Site.objects.get_current(), 'thread': t, }) email = EmailMessage( subject=mail_subject + ' ' + striptags(t.title), body=mail_tpl.render(c), from_email=mail_from, bcc=[s.author.email for s in t.subscription_set.all()], ) email.send(fail_silently=True) return HttpResponseRedirect(p.get_absolute_url()) else: form = ReplyForm() return render_to_response( 'forum/reply.html', RequestContext(request, { 'form': form, 'forum': t.forum, 'thread': t, }))
def edit(request, thread): """ If a thread isn't closed, and the user is logged in, post a reply to a thread. Note we don't have "nested" replies at this stage. """ if not request.user.is_authenticated(): return HttpResponseServerError() t = get_object_or_404(Thread, pk=thread) if t.closed: return HttpResponseServerError() if not Forum.objects.has_access(t.forum, request.user.groups.all()): return HttpResponseForbidden() if request.method == "POST": form = ReplyForm(data=request.POST, files=request.FILES) if form.is_valid(): body = form.cleaned_data['body'] p = Post( thread=t, author=request.user, body=body, time=datetime.now(), ) p.save() sub = Subscription.objects.filter(thread=t, author=request.user) if form.cleaned_data.get('subscribe',False): if not sub: s = Subscription( author=request.user, thread=t ) s.save() else: if sub: sub.delete() # Subscriptions are updated now send mail to all the authors subscribed in # this thread. mail_subject = '' try: mail_subject = settings.FORUM_MAIL_PREFIX except AttributeError: mail_subject = '[Forum]' mail_from = '' try: mail_from = settings.FORUM_MAIL_FROM except AttributeError: mail_from = settings.DEFAULT_FROM_EMAIL mail_tpl = loader.get_template('forum/notify.txt') c = Context({ 'body': wordwrap(striptags(body), 72), 'site' : Site.objects.get_current(), 'thread': t, }) email = EmailMessage( subject=mail_subject+' '+striptags(t.title), body= mail_tpl.render(c), from_email=mail_from, to=[mail_from], bcc=[s.author.email for s in t.subscription_set.all()],) email.send(fail_silently=True) for attachedfilefield in form.files: #file_path = '%s%s' % (settings.MEDIA_ROOT, form.files[attachedfilefield]) attachment_file = form.files[attachedfilefield] attach=Attachment() attach.handle_uploaded_attachment(p, attachment_file, request.user, attachment_file.name, t.title ) return HttpResponseRedirect(p.get_absolute_url()) else: post_id = request.GET.get('pid', 0) if post_id ==0: return HttpResponseServerError(_("The Post Do Not Exist")) try: p = Post.objects.all().get(id=post_id) except Post.DoesNotExist: raise Http404(_("Not Found")) body=p.body initial = {'subscribe': True, 'body':body} form = ReplyForm(initial=initial) return render_to_response('forum/edit.html', RequestContext(request, { 'form': form, 'post': p }))