def process_response(self, request, response): # Update last visit time after request finished processing. user = None try: if request.user.is_authenticated(): user = request.user except: pass if user: profile = request.user.profile if profile.last_visit is None: profile.last_visit = datetime.datetime.now() profile.last_ip_address = get_client_ip(request) profile.save() else: duration = datetime.datetime.now() - profile.last_visit if duration.seconds > settings.ZDS_APP['member'][ 'update_last_visit_interval']: profile.last_visit = datetime.datetime.now() profile.last_ip_address = get_client_ip(request) profile.save() if not profile.can_read: logout(request) return response
def send_post( request, topic, author, text, ): post = Post() post.topic = topic post.author = author post.pubdate = datetime.now() if topic.last_message is not None: post.position = topic.last_message.position + 1 else: post.position = 1 post.update_content( text, on_error=lambda m: messages.error( request, _('Erreur du serveur Markdown:\n{}').format('\n- '.join(m)))) post.ip_address = get_client_ip(request) post.hat = get_hat_from_request(request) post.save() topic.last_message = post topic.save() return topic
def form_valid(self, form): if self.check_as and self.object.antispam(self.request.user): raise PermissionDenied if "preview" in self.request.POST: return self.form_invalid(form) is_new = False if self.reaction: # it's an edition edit = CommentEdit() edit.comment = self.reaction edit.editor = self.request.user edit.original_text = self.reaction.text edit.save() self.reaction.update = datetime.now() self.reaction.editor = self.request.user self.reaction.hat = get_hat_from_request(self.request, self.reaction.author) else: self.reaction = ContentReaction() self.reaction.pubdate = datetime.now() self.reaction.author = self.request.user self.reaction.position = self.object.get_note_count() + 1 self.reaction.related_content = self.object self.reaction.hat = get_hat_from_request(self.request) is_new = True # also treat alerts if editor is a moderator if self.request.user != self.reaction.author and not is_new: alerts = Alert.objects.filter(comment__pk=self.reaction.pk, solved=False) for alert in alerts: alert.solve(self.request.user, _("Le message a été modéré.")) self.reaction.update_content( form.cleaned_data["text"], on_error=lambda m: messages.error( self.request, _("Erreur du serveur Markdown: {}").format("\n- ".join(m))), ) self.reaction.ip_address = get_client_ip(self.request) self.reaction.save() if is_new: # we first need to save the reaction self.object.last_note = self.reaction self.object.save(update_date=False) self.success_url = self.reaction.get_absolute_url() return super().form_valid(form)
def process_response(self, request, response): # Update last visit time after request finished processing. try: if request.user.is_authenticated(): user = request.user else: user = None except: user = None if user is not None: profile = request.user.profile if profile.last_visit is None: profile.last_visit = datetime.datetime.now() profile.last_ip_address = get_client_ip(request) profile.save() else: duration = datetime.datetime.now() - profile.last_visit if duration.seconds > 600: profile.last_visit = datetime.datetime.now() profile.last_ip_address = get_client_ip(request) profile.save() return response
def form_valid(self, form): profile = self.create_profile(form.data) profile.last_ip_address = get_client_ip(self.request) profile.username_skeleton = Profile.find_username_skeleton(profile.user.username) self.save_profile(profile) token = self.generate_token(profile.user) try: self.send_email(token, profile.user) except Exception as e: logging.getLogger(__name__).warning("Mail not sent", exc_info=e) messages.warning(self.request, _("Impossible d'envoyer l'email.")) self.object = None return self.form_invalid(form) return render(self.request, self.get_success_template())
def matomo_track(self, request): client_user_agent = request.META.get("HTTP_USER_AGENT", "") client_referer = request.META.get("HTTP_REFERER", "") client_accept_language = request.META.get("HTTP_ACCEPT_LANGUAGE", "") client_url = f"{request.scheme}://{request.get_host()}{request.path}" if settings.ZDS_APP["site"]["matomo_tracking_enabled"]: self.queue.put({ "client_user_agent": client_user_agent, "client_referer": client_referer, "client_accept_language": client_accept_language, "client_url": client_url, "datetime": datetime.now().time(), "r_path": request.path, "address_ip": get_client_ip(request), })
def send_post(request, topic, author, text,): post = Post() post.topic = topic post.author = author post.update_content(text) post.pubdate = datetime.now() if topic.last_message is not None: post.position = topic.last_message.position + 1 else: post.position = 1 post.ip_address = get_client_ip(request) post.save() topic.last_message = post topic.save() return topic
def form_valid(self, form): if self.check_as and self.object.antispam(self.request.user): raise PermissionDenied if 'preview' in self.request.POST: # previewing return self.form_invalid(form) is_new = False if self.reaction: # it's an edition self.reaction.update = datetime.now() self.reaction.editor = self.request.user else: self.reaction = ContentReaction() self.reaction.pubdate = datetime.now() self.reaction.author = self.request.user self.reaction.position = self.object.get_note_count() + 1 self.reaction.related_content = self.object is_new = True # also treat alerts if editor is a moderator if self.request.user != self.reaction.author and not is_new: alerts = Alert.objects.filter(comment__pk=self.reaction.pk, solved=False) for alert in alerts: alert.solve(self.reaction, self.request.user, _(u'Résolu par édition.')) self.reaction.update_content(form.cleaned_data['text']) self.reaction.ip_address = get_client_ip(self.request) self.reaction.save() if is_new: # we first need to save the reaction self.object.last_note = self.reaction self.object.save(update_date=False) self.success_url = self.reaction.get_absolute_url() return super(SendNoteFormView, self).form_valid(form)
def send_post(request, topic, author, text,): post = Post() post.topic = topic post.author = author post.pubdate = datetime.now() if topic.last_message is not None: post.position = topic.last_message.position + 1 else: post.position = 1 post.update_content( text, on_error=lambda m: messages.error( request, _('Erreur du serveur Markdown:\n{}').format('\n- '.join(m)))) post.ip_address = get_client_ip(request) post.hat = get_hat_from_request(request) post.save() topic.last_message = post topic.save() return topic
def add_newsletter(request): if request.method == 'POST': form = NewsletterForm(request.POST) my_ip = get_client_ip(request) already = Newsletter.objects.filter(ip = my_ip).count() if form.is_valid() and already == 0 : data = form.data print data['email'] nl = Newsletter() nl.email = data['email'] nl.ip = my_ip nl.save() return render_template('newsletter/confirm.html') else: # TODO: add errors to the form and return it return render_template('newsletter/failed.html') else: form = NewsletterForm() return render_template('newsletter/new_newsletter.html', { 'form': form })
def answer(request): """Adds an answer from a user to a topic.""" try: topic_pk = request.GET["sujet"] except KeyError: raise Http404 # Retrieve current topic. g_topic = get_object_or_404(Topic, pk=topic_pk) if not g_topic.forum.can_read(request.user): raise PermissionDenied # Making sure posting is allowed if g_topic.is_locked: raise PermissionDenied # Check that the user isn't spamming if g_topic.antispam(request.user): raise PermissionDenied last_post_pk = g_topic.last_message.pk # Retrieve 10 last posts of the current topic. posts = \ Post.objects.filter(topic=g_topic) \ .prefetch_related() \ .order_by("-pubdate" )[:10] # User would like preview his post or post a new post on the topic. if request.method == "POST": data = request.POST newpost = last_post_pk != int(data["last_post"]) # Using the « preview button », the « more » button or new post if "preview" in data or newpost: form = PostForm(g_topic, request.user, initial={"text": data["text" ]}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Saving the message form = PostForm(g_topic, request.user, request.POST) if form.is_valid(): data = form.data post = Post() post.topic = g_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(data["text"]) post.pubdate = datetime.now() post.position = g_topic.get_post_count() + 1 post.ip_address = get_client_ip(request) post.save() g_topic.last_message = post g_topic.save() #Send mail subject = "ZDS - Notification : " + g_topic.title from_email = "Zeste de Savoir <{0}>".format(settings.MAIL_NOREPLY) followers = g_topic.get_followers_by_email() for follower in followers: receiver = follower.user if receiver == request.user: continue pos = post.position - 1 last_read = TopicRead.objects.filter( topic=g_topic, post__position=pos, user=receiver).count() if last_read > 0: message_html = get_template('email/notification/new.html') \ .render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) message_txt = get_template('email/notification/new.txt').render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) msg = EmailMultiAlternatives( subject, message_txt, from_email, [ receiver.email]) msg.attach_alternative(message_html, "text/html") msg.send() # Follow topic on answering if not g_topic.is_followed(user=request.user): follow(g_topic) return redirect(post.get_absolute_url()) else: return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Actions from the editor render to new.html. text = "" # Using the quote button if "cite" in request.GET: post_cite_pk = request.GET["cite"] post_cite = Post.objects.get(pk=post_cite_pk) if not post_cite.is_visible: raise PermissionDenied for line in post_cite.text.splitlines(): text = text + "> " + line + "\n" text = u"{0}Source:[{1}]({2}{3})".format( text, post_cite.author.username, settings.SITE_URL, post_cite.get_absolute_url()) form = PostForm(g_topic, request.user, initial={"text": text}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "form": form, })
def new(request): """Creates a new topic in a forum.""" try: forum_pk = request.GET["forum"] except KeyError: raise Http404 forum = get_object_or_404(Forum, pk=forum_pk) if not forum.can_read(request.user): raise PermissionDenied if request.method == "POST": # If the client is using the "preview" button if "preview" in request.POST: form = TopicForm(initial={"title": request.POST["title"], "subtitle": request.POST["subtitle"], "text": request.POST["text"]}) return render_template("forum/topic/new.html", {"forum": forum, "form": form, "text": request.POST["text"]}) form = TopicForm(request.POST) data = form.data if form.is_valid(): # Treat title (tags, title) = get_tag_by_title(data["title"]) # Creating the thread n_topic = Topic() n_topic.forum = forum n_topic.title = title n_topic.subtitle = data["subtitle"] n_topic.pubdate = datetime.now() n_topic.author = request.user n_topic.save() # add tags n_topic.add_tags(tags) n_topic.save() # Adding the first message post = Post() post.topic = n_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(request.POST["text"]) post.pubdate = datetime.now() post.position = 1 post.ip_address = get_client_ip(request) post.save() n_topic.last_message = post n_topic.save() # Follow the topic follow(n_topic) return redirect(n_topic.get_absolute_url()) else: form = TopicForm() return render_template("forum/topic/new.html", {"forum": forum, "form": form})
def answer(request): """Adds an answer from a user to a topic.""" try: topic_pk = request.GET["sujet"] except: # problem in variable format raise Http404 # Retrieve current topic. g_topic = get_object_or_404(Topic, pk=topic_pk) if not g_topic.forum.can_read(request.user): raise PermissionDenied # Making sure posting is allowed if g_topic.is_locked: raise PermissionDenied # Check that the user isn't spamming if g_topic.antispam(request.user): raise PermissionDenied last_post_pk = g_topic.last_message.pk # Retrieve last posts of the current topic. posts = Post.objects.filter(topic=g_topic) \ .prefetch_related() \ .order_by("-pubdate")[:settings.POSTS_PER_PAGE] # User would like preview his post or post a new post on the topic. if request.method == "POST": data = request.POST newpost = last_post_pk != int(data["last_post"]) # Using the « preview button », the « more » button or new post if "preview" in data or newpost: form = PostForm(g_topic, request.user, initial={"text": data["text"]}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Saving the message form = PostForm(g_topic, request.user, request.POST) if form.is_valid(): data = form.data post = Post() post.topic = g_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(data["text"]) post.pubdate = datetime.now() post.position = g_topic.get_post_count() + 1 post.ip_address = get_client_ip(request) post.save() g_topic.last_message = post g_topic.save() #Send mail subject = "ZDS - Notification : " + g_topic.title from_email = "Zeste de Savoir <{0}>".format(settings.MAIL_NOREPLY) followers = g_topic.get_followers_by_email() for follower in followers: receiver = follower.user if receiver == request.user: continue pos = post.position - 1 last_read = TopicRead.objects.filter( topic=g_topic, post__position=pos, user=receiver).count() if last_read > 0: message_html = get_template('email/notification/new.html') \ .render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) message_txt = get_template('email/notification/new.txt').render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) msg = EmailMultiAlternatives( subject, message_txt, from_email, [ receiver.email]) msg.attach_alternative(message_html, "text/html") msg.send() # Follow topic on answering if not g_topic.is_followed(user=request.user): follow(g_topic) return redirect(post.get_absolute_url()) else: return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Actions from the editor render to new.html. text = "" # Using the quote button if "cite" in request.GET: post_cite_pk = request.GET["cite"] post_cite = Post.objects.get(pk=post_cite_pk) if not post_cite.is_visible: raise PermissionDenied for line in post_cite.text.splitlines(): text = text + "> " + line + "\n" text = u"{0}Source:[{1}]({2}{3})".format( text, post_cite.author.username, settings.SITE_URL, post_cite.get_absolute_url()) form = PostForm(g_topic, request.user, initial={"text": text}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "form": form, })
def new(request): """Creates a new topic in a forum.""" try: forum_pk = request.GET["forum"] except: # problem in variable format raise Http404 forum = get_object_or_404(Forum, pk=forum_pk) if not forum.can_read(request.user): raise PermissionDenied if request.method == "POST": # If the client is using the "preview" button if "preview" in request.POST: form = TopicForm(initial={"title": request.POST["title"], "subtitle": request.POST["subtitle"], "text": request.POST["text"]}) return render_template("forum/topic/new.html", {"forum": forum, "form": form, "text": request.POST["text"]}) form = TopicForm(request.POST) data = form.data if form.is_valid(): # Treat title (tags, title) = get_tag_by_title(data["title"]) # Creating the thread n_topic = Topic() n_topic.forum = forum n_topic.title = title n_topic.subtitle = data["subtitle"] n_topic.pubdate = datetime.now() n_topic.author = request.user n_topic.save() # add tags n_topic.add_tags(tags) n_topic.save() # Adding the first message post = Post() post.topic = n_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(request.POST["text"]) post.pubdate = datetime.now() post.position = 1 post.ip_address = get_client_ip(request) post.save() n_topic.last_message = post n_topic.save() # Follow the topic follow(n_topic) return redirect(n_topic.get_absolute_url()) else: form = TopicForm() return render_template("forum/topic/new.html", {"forum": forum, "form": form})
def answer(request): """Adds an answer from a user to an article.""" try: article_pk = request.GET['article'] except KeyError: raise Http404 # Retrieve current article. article = get_object_or_404(Article, pk=article_pk) # Making sure reactioning is allowed if article.is_locked: raise PermissionDenied # Check that the user isn't spamming if article.antispam(request.user): raise PermissionDenied # Retrieve 3 last reactions of the currenta article. reactions = Reaction.objects\ .filter(article=article)\ .order_by('-pubdate')[:3] # If there is a last reaction for the article, we save his pk. # Otherwise, we save 0. if article.last_reaction: last_reaction_pk = article.last_reaction.pk else: last_reaction_pk = 0 # User would like preview his post or post a new reaction on the article. if request.method == 'POST': data = request.POST newreaction = last_reaction_pk != int(data['last_reaction']) # Using the « preview button », the « more » button or new reaction if 'preview' in data or newreaction: form = ReactionForm(article, request.user, initial={'text': data['text']}) return render_template( 'article/reaction/new.html', { 'article': article, 'last_reaction_pk': last_reaction_pk, 'newreaction': newreaction, 'form': form }) # Saving the message else: form = ReactionForm(article, request.user, request.POST) if form.is_valid(): data = form.data reaction = Reaction() reaction.article = article reaction.author = request.user reaction.text = data['text'] reaction.text_html = emarkdown(data['text']) reaction.pubdate = datetime.now() reaction.position = article.get_reaction_count() + 1 reaction.ip_address = get_client_ip(request) reaction.save() article.last_reaction = reaction article.save() return redirect(reaction.get_absolute_url()) else: return render_template( 'article/reaction/new.html', { 'article': article, 'last_reaction_pk': last_reaction_pk, 'newreaction': newreaction, 'form': form }) # Actions from the editor render to new.html. else: text = '' # Using the quote button if 'cite' in request.GET: reaction_cite_pk = request.GET['cite'] reaction_cite = Reaction.objects.get(pk=reaction_cite_pk) if not reaction_cite.is_visible: raise PermissionDenied for line in reaction_cite.text.splitlines(): text = text + '> ' + line + '\n' text = u'{0}Source:[{1}]({2}{3})'.format( text, reaction_cite.author.username, settings.SITE_URL, reaction_cite.get_absolute_url()) form = ReactionForm(article, request.user, initial={'text': text}) return render_template( 'article/reaction/new.html', { 'article': article, 'reactions': reactions, 'last_reaction_pk': last_reaction_pk, 'form': form })
def send_post( request, topic, author, text, send_by_mail=False, ): post = Post() post.topic = topic post.author = author post.update_content(text) post.pubdate = datetime.now() if topic.last_message is not None: post.position = topic.last_message.position + 1 else: post.position = 1 post.ip_address = get_client_ip(request) post.save() topic.last_message = post topic.save() # Send mail if send_by_mail: subject = u"{} - {} : {}".format( settings.ZDS_APP['site']['litteral_name'], _(u'Forum'), topic.title) from_email = "{} <{}>".format( settings.ZDS_APP['site']['litteral_name'], settings.ZDS_APP['site']['email_noreply']) followers = topic.get_followers_by_email() for follower in followers: receiver = follower.user if receiver == post.author: continue last_read = TopicRead.objects.filter(topic=topic, post__position=post.position - 1, user=receiver).count() if last_read > 0: context = { 'username': receiver.username, 'title': topic.title, 'url': settings.ZDS_APP['site']['url'] + post.get_absolute_url(), 'author': post.author.username, 'site_name': settings.ZDS_APP['site']['litteral_name'] } message_html = render_to_string('email/forum/new_post.html', context) message_txt = render_to_string('email/forum/new_post.txt', context) msg = EmailMultiAlternatives(subject, message_txt, from_email, [receiver.email]) msg.attach_alternative(message_html, "text/html") msg.send() # Follow topic on answering if not topic.is_followed(user=post.author): follow(topic) return topic
def answer(request): ''' Adds an answer from a user to an article ''' try: article_pk = request.GET['article'] except KeyError: raise Http404 g_article = get_object_or_404(Article, pk=article_pk) reactions = Reaction.objects.filter( article=g_article).order_by('-pubdate')[:3] if g_article.last_reaction: last_reaction_pk = g_article.last_reaction.pk else: last_reaction_pk = 0 # Making sure reactioning is allowed if g_article.is_locked: raise Http404 # Check that the user isn't spamming if g_article.antispam(request.user): raise Http404 # If we just sent data if request.method == 'POST': data = request.POST newreaction = last_reaction_pk != int(data['last_reaction']) # Using the « preview button », the « more » button or new reaction if 'preview' in data or 'more' in data or newreaction: return render_template( 'article/answer.html', { 'text': data['text'], 'article': g_article, 'reactions': reactions, 'last_reaction_pk': last_reaction_pk, 'newreaction': newreaction }) # Saving the message else: form = ReactionForm(request.POST) if form.is_valid() and data['text'].strip() != '': data = form.data reaction = Reaction() reaction.article = g_article reaction.author = request.user reaction.text = data['text'] reaction.text_html = emarkdown(data['text']) reaction.pubdate = datetime.now() reaction.position = g_article.get_reaction_count() + 1 reaction.ip_address = get_client_ip(request) reaction.save() g_article.last_reaction = reaction g_article.save() return redirect(reaction.get_absolute_url()) else: raise Http404 else: text = '' # Using the quote button if 'cite' in request.GET: reaction_cite_pk = request.GET['cite'] reaction_cite = Reaction.objects.get(pk=reaction_cite_pk) for line in reaction_cite.text.splitlines(): text = text + '> ' + line + '\n' text = u'**{0} a écrit :**\n{1}\n'.format( reaction_cite.author.username, text) return render_template( 'article/answer.html', { 'article': g_article, 'text': text, 'reactions': reactions, 'last_reaction_pk': last_reaction_pk })
def answer(request): """Adds an answer from a user to an article.""" try: article_pk = request.GET['article'] except KeyError: raise Http404 # Retrieve current article. article = get_object_or_404(Article, pk=article_pk) # Making sure reactioning is allowed if article.is_locked: raise PermissionDenied # Check that the user isn't spamming if article.antispam(request.user): raise PermissionDenied # Retrieve 3 last reactions of the currenta article. reactions = Reaction.objects\ .filter(article=article)\ .order_by('-pubdate')[:3] # If there is a last reaction for the article, we save his pk. # Otherwise, we save 0. if article.last_reaction: last_reaction_pk = article.last_reaction.pk else: last_reaction_pk = 0 # User would like preview his post or post a new reaction on the article. if request.method == 'POST': data = request.POST newreaction = last_reaction_pk != int(data['last_reaction']) # Using the « preview button », the « more » button or new reaction if 'preview' in data or newreaction: form = ReactionForm(article, request.user, initial={ 'text': data['text'] }) return render_template('article/reaction/new.html', { 'article': article, 'last_reaction_pk': last_reaction_pk, 'newreaction': newreaction, 'form': form }) # Saving the message else: form = ReactionForm(article, request.user, request.POST) if form.is_valid(): data = form.data reaction = Reaction() reaction.article = article reaction.author = request.user reaction.text = data['text'] reaction.text_html = emarkdown(data['text']) reaction.pubdate = datetime.now() reaction.position = article.get_reaction_count() + 1 reaction.ip_address = get_client_ip(request) reaction.save() article.last_reaction = reaction article.save() return redirect(reaction.get_absolute_url()) else: return render_template('article/reaction/new.html', { 'article': article, 'last_reaction_pk': last_reaction_pk, 'newreaction': newreaction, 'form': form }) # Actions from the editor render to new.html. else: text = '' # Using the quote button if 'cite' in request.GET: reaction_cite_pk = request.GET['cite'] reaction_cite = Reaction.objects.get(pk=reaction_cite_pk) if not reaction_cite.is_visible: raise PermissionDenied for line in reaction_cite.text.splitlines(): text = text + '> ' + line + '\n' text = u'{0}Source:[{1}]({2}{3})'.format( text, reaction_cite.author.username, settings.SITE_URL, reaction_cite.get_absolute_url()) form = ReactionForm(article, request.user, initial={ 'text': text }) return render_template('article/reaction/new.html', { 'article': article, 'reactions': reactions, 'last_reaction_pk': last_reaction_pk, 'form': form })
def answer(request): ''' Adds an answer from a user to an article ''' try: article_pk = request.GET['article'] except KeyError: raise Http404 g_article = get_object_or_404(Article, pk=article_pk) reactions = Reaction.objects.filter(article=g_article).order_by('-pubdate')[:3] if g_article.last_reaction: last_reaction_pk = g_article.last_reaction.pk else: last_reaction_pk=0 # Making sure reactioning is allowed if g_article.is_locked: raise Http404 # Check that the user isn't spamming if g_article.antispam(request.user): raise Http404 # If we just sent data if request.method == 'POST': data = request.POST newreaction = last_reaction_pk != int(data['last_reaction']) # Using the « preview button », the « more » button or new reaction if 'preview' in data or 'more' in data or newreaction: return render_template('article/answer.html', { 'text': data['text'], 'article': g_article, 'reactions': reactions, 'last_reaction_pk': last_reaction_pk, 'newreaction': newreaction }) # Saving the message else: form = ReactionForm(request.POST) if form.is_valid() and data['text'].strip() !='': data = form.data reaction = Reaction() reaction.article = g_article reaction.author = request.user reaction.text = data['text'] reaction.text_html = emarkdown(data['text']) reaction.pubdate = datetime.now() reaction.position = g_article.get_reaction_count() + 1 reaction.ip_address = get_client_ip(request) reaction.save() g_article.last_reaction = reaction g_article.save() return redirect(reaction.get_absolute_url()) else: raise Http404 else: text = '' # Using the quote button if 'cite' in request.GET: reaction_cite_pk = request.GET['cite'] reaction_cite = Reaction.objects.get(pk=reaction_cite_pk) for line in reaction_cite.text.splitlines(): text = text + '> ' + line + '\n' text = u'**{0} a écrit :**\n{1}\n'.format( reaction_cite.author.username, text) return render_template('article/answer.html', { 'article': g_article, 'text': text, 'reactions': reactions, 'last_reaction_pk': last_reaction_pk })
def login_view(request): """Logs user in.""" next_page = request.GET.get("next", "/") if next_page in [ reverse("member-login"), reverse("register-member"), reverse("member-logout") ]: next_page = "/" csrf_tk = {"next_page": next_page} csrf_tk.update(csrf(request)) error = False if request.method != "POST": form = LoginForm() else: form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user is None: initial = {"username": username} if User.objects.filter(username=username).exists(): messages.error( request, _("Le mot de passe saisi est incorrect. " "Cliquez sur le lien « Mot de passe oublié ? » " "si vous ne vous en souvenez plus."), ) else: messages.error( request, _("Ce nom d’utilisateur est inconnu. " "Si vous ne possédez pas de compte, " "vous pouvez vous inscrire."), ) form = LoginForm(initial=initial) if next_page is not None: form.helper.form_action += "?next=" + next_page csrf_tk["error"] = error csrf_tk["form"] = form return render(request, "member/login.html", { "form": form, "csrf_tk": csrf_tk }) profile = get_object_or_404(Profile, user=user) if not user.is_active: messages.error( request, _("Vous n'avez pas encore activé votre compte, " "vous devez le faire pour pouvoir vous " "connecter sur le site. Regardez dans vos " "mails : {}.").format(user.email), ) elif not profile.can_read_now(): messages.error( request, _("Vous n'êtes pas autorisé à vous connecter " "sur le site, vous avez été banni par un " "modérateur."), ) else: login(request, user) request.session["get_token"] = generate_token() if "remember" not in request.POST: request.session.set_expiry(0) profile.last_ip_address = get_client_ip(request) profile.save() # Redirect the user if needed. # Set the cookie for Clem smileys. # (For people switching account or clearing cookies # after a browser session.) try: response = redirect(resolve(next_page).url_name) except NoReverseMatch: response = redirect(next_page) except Resolver404: response = redirect(reverse("homepage")) return response if next_page is not None: form.helper.form_action += "?next=" + next_page csrf_tk["error"] = error csrf_tk["form"] = form return render(request, "member/login.html", { "form": form, "csrf_tk": csrf_tk, "next_page": next_page })
def answer(request): ''' Adds an answer from a user to a topic ''' try: topic_pk = request.GET['sujet'] except KeyError: raise Http404 g_topic = get_object_or_404(Topic, pk=topic_pk) if not g_topic.forum.can_read(request.user): raise Http404 posts = Post.objects.filter(topic=g_topic).order_by('-pubdate')[:3] last_post_pk = g_topic.last_message.pk # Making sure posting is allowed if g_topic.is_locked: raise Http404 # Check that the user isn't spamming if g_topic.antispam(request.user): raise Http404 # If we just sent data if request.method == 'POST': data = request.POST newpost = last_post_pk != int(data['last_post']) # Using the « preview button », the « more » button or new post if 'preview' in data or 'more' in data or newpost: return render_template( 'forum/answer.html', { 'text': data['text'], 'topic': g_topic, 'posts': posts, 'last_post_pk': last_post_pk, 'newpost': newpost }) # Saving the message else: form = PostForm(request.POST) if form.is_valid() and data['text'].strip() != '': data = form.data post = Post() post.topic = g_topic post.author = request.user post.text = data['text'] post.text_html = emarkdown(data['text']) post.pubdate = datetime.now() post.position = g_topic.get_post_count() + 1 post.ip_address = get_client_ip(request) post.save() g_topic.last_message = post g_topic.save() # Follow topic on answering if not g_topic.is_followed(): follow(g_topic) return redirect(post.get_absolute_url()) else: raise Http404 else: text = '' # Using the quote button if 'cite' in request.GET: post_cite_pk = request.GET['cite'] post_cite = Post.objects.get(pk=post_cite_pk) for line in post_cite.text.splitlines(): text = text + '> ' + line + '\n' text = u'**{0} a écrit :**\n{1}\n'.format( post_cite.author.username, text) return render_template( 'forum/answer.html', { 'topic': g_topic, 'text': text, 'posts': posts, 'last_post_pk': last_post_pk })
def new(request): ''' Creates a new topic in a forum ''' try: forum_pk = request.GET['forum'] except KeyError: raise Http404 forum = get_object_or_404(Forum, pk=forum_pk) if request.method == 'POST': # If the client is using the "preview" button if 'preview' in request.POST: return render_template( 'forum/new.html', { 'forum': forum, 'title': request.POST['title'], 'subtitle': request.POST['subtitle'], 'text': request.POST['text'], }) form = TopicForm(request.POST) if form.is_valid() and data['text'].strip() != '': data = form.data # Creating the thread n_topic = Topic() n_topic.forum = forum n_topic.title = data['title'] n_topic.subtitle = data['subtitle'] n_topic.pubdate = datetime.now() n_topic.author = request.user n_topic.save() # Adding the first message post = Post() post.topic = n_topic post.author = request.user post.text = data['text'] post.text_html = emarkdown(request.POST['text']) post.pubdate = datetime.now() post.position = 1 post.ip_address = get_client_ip(request) post.save() n_topic.last_message = post n_topic.save() # Follow the topic follow(n_topic) return redirect(n_topic.get_absolute_url()) else: # TODO: add errors to the form and return it raise Http404 else: form = TopicForm() return render_template('forum/new.html', { 'form': form, 'forum': forum })