removed wtform

This commit is contained in:
2024-12-16 18:43:06 +01:00
parent 3b41520da9
commit 1c24b993bb
13 changed files with 222 additions and 223 deletions

View File

@@ -1,50 +0,0 @@
from wtforms import Form, StringField, TextAreaField, SelectField, DateTimeField
from wtforms import IntegerField, PasswordField
from wtforms.validators import InputRequired, Length, EqualTo
from wtforms.widgets import HiddenInput
strip_filter = lambda x: x.strip() if x else None
class BlogCreateForm(Form):
title = StringField('Titre', validators=[InputRequired(), Length(min=1, max=255)],
filters=[strip_filter])
body = TextAreaField('Corps du texte', validators=[InputRequired(), Length(min=1)],
filters=[strip_filter])
tag = SelectField('Tag')
author = StringField('Auteur', validators=[InputRequired(), Length(min=1, max=50)],
filters=[strip_filter])
status = SelectField('Statut', choices=[('brouillon','Brouillon'),('privé','Privé'),('publié','Publié')])
created = DateTimeField('Créé le', validators=[InputRequired()])
class BlogUpdateForm(BlogCreateForm):
id = IntegerField(widget=HiddenInput())
created = DateTimeField('Créé le', validators=[InputRequired()])
class BlogSearchForm(Form):
criteria = StringField('Critère', validators=[InputRequired(), Length(min=3, max=45)],
filters=[strip_filter])
class UserCreateForm(Form):
id = IntegerField(widget=HiddenInput())
name = StringField('Nom', validators=[InputRequired(), Length(min=1, max=255)],
filters=[strip_filter])
password = PasswordField('Mot de passe')
confirm = PasswordField('Confirmer', validators=[EqualTo('password', message='Les 2 Passwords doivent être identiques')])
class TopicForm(Form):
topic = StringField('Topic', validators=[InputRequired(), Length(min=1, max=25)],
filters=[strip_filter])
topic_name = StringField('Intitulé', validators=[InputRequired(), Length(min=1, max=25)],
filters=[strip_filter])
topic_quote = TextAreaField('Citation', validators=[InputRequired(), Length(min=1)],
filters=[strip_filter])
class TagForm(Form):
id = IntegerField(widget=HiddenInput())
tag = StringField('Tag', validators=[InputRequired(), Length(min=1, max=25)],
filters=[strip_filter])
tag_name = StringField('Intitulé', validators=[InputRequired(), Length(min=1, max=25)],
filters=[strip_filter])

View File

@@ -4,7 +4,7 @@ from .default import (
) )
def get_entries_by_topic(request, topic, tag): def get_entries_by_topic(request, topic, tag):
query = f"SELECT * FROM entries WHERE topic_id = {topic}" query = "SELECT *, strftime('%d/%m/%Y', created) AS create_date FROM entries WHERE topic_id = '{0}'".format(topic)
if request.authenticated_userid == None: if request.authenticated_userid == None:
# if user is anonym, display only published posts # if user is anonym, display only published posts
query = query + " AND status='publié'" query = query + " AND status='publié'"
@@ -13,7 +13,7 @@ def get_entries_by_topic(request, topic, tag):
# if user is not 'admin', hide admin posts # if user is not 'admin', hide admin posts
query = query + " AND tag =! '_admin'" query = query + " AND tag =! '_admin'"
if tag != '': if tag != '':
query = query + " AND tag = {tag}" query = query + " AND tag = '{0}'".format(tag)
query = query + " ORDER BY tag, title;" query = query + " ORDER BY tag, title;"
results = request.dbsession.execute(query).fetchall() results = request.dbsession.execute(query).fetchall()
@@ -21,7 +21,7 @@ def get_entries_by_topic(request, topic, tag):
def get_entries_by_criteria(request, criteria): def get_entries_by_criteria(request, criteria):
search = "%{}%".format(criteria) search = "%{}%".format(criteria)
query = f"SELECT * FROM entries WHERE title = {search} or body = {search}" query = f"SELECT *, strftime('%d/%m/%Y', edited) AS edit_date FROM entries WHERE title like '{search}' or body like '{search}'"
if request.authenticated_userid == None: if request.authenticated_userid == None:
# if user is anonym, display only published posts # if user is anonym, display only published posts
query = query + " AND status='publié'" query = query + " AND status='publié'"
@@ -34,13 +34,14 @@ def get_entries_by_criteria(request, criteria):
return results return results
def get_entries_by_id(request, _id): def get_entries_by_id(request, _id):
query = "SELECT * FROM entries WHERE id=:id;" query = """SELECT *, strftime('%d/%m/%Y', created) AS create_date,
strftime('%d/%m/%Y', edited) AS edit_date FROM entries WHERE id=:id;"""
results = request.dbsession.execute(query, {'id':_id}).first() results = request.dbsession.execute(query, {'id':_id}).first()
return results return results
def get_last_created(request): def get_last_created(request):
# gest the 10 last created posts # gest the 10 last created posts
query = "SELECT strftime('%d/%m/%Y', created) AS create_date, title, author, status FROM entries WHERE topic_id <> '_admin'" query = "SELECT strftime('%d/%m/%Y', created) AS create_date, id, title, author, status FROM entries WHERE topic_id <> '_admin'"
if request.authenticated_userid == None: if request.authenticated_userid == None:
# if user is anonym, display only published posts # if user is anonym, display only published posts
query = query + " AND status='publié'" query = query + " AND status='publié'"
@@ -74,7 +75,7 @@ def get_tags_byTopic(request, topic):
def get_tags_byId(request, id): def get_tags_byId(request, id):
query = "SELECT * FROM tags WHERE id=:id;" query = "SELECT * FROM tags WHERE id=:id;"
results = request.dbsession.execute(query, {'topic':id}).first() results = request.dbsession.execute(query, {'id':id}).first()
return results return results
def get_topic_byTopic(request, id): def get_topic_byTopic(request, id):
@@ -89,15 +90,69 @@ def get_topics(request):
results = request.dbsession.execute(query, {'topic':id}).all() results = request.dbsession.execute(query, {'topic':id}).all()
return results return results
def entries_delete(request, id): def delete_entry(request, id):
query = "DELETE FROM entries WHERE id = :id ;" query = "DELETE FROM entries WHERE id = :id ;"
execute_query(request, query, {'id': id}) execute_query(request, query, {'id': id})
def tags_delete(request, id): def delete_tag(request, id):
query = "DELETE FROM tags WHERE id = :id ;" query = "DELETE FROM tags WHERE id = :id ;"
execute_query(request, query, {'id': id}) execute_query(request, query, {'id': id})
def topics_delete(request, id): def delete_topic(request, topic):
query = "DELETE FROM topics WHERE topic = :id ;" query = "DELETE FROM topics WHERE topic = :topic ;"
execute_query(request, query, {'id': id}) execute_query(request, query, {'topic': topic})
def update_entry(request, blog_id, new_values):
# formater les champs
s = ''
for param in new_values.keys():
if s:
s += ",%s=:%s" % (param, param)
else:
s = "%s=:%s" % (param, param)
import pdb;pdb.set_trace()
if blog_id == '0':
query = """INSERT INTO entries (title, body, created, edited, topic_id, tag, author, status, creator, editor)
VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{8}')""".format(
new_values['title'], new_values['body'], new_values['created'], new_values['created'],
new_values['topic_id'], new_values['tag'], new_values['author'], new_values['status'],
new_values['editor'], new_values['editor'],)
else:
new_values['id'] = blog_id
query = "UPDATE entries SET %s WHERE id = :id;" % s
execute_query(request, query, new_values)
def update_tag(request, id, new_values):
# formater les champs
s = ''
for param in new_values.keys():
if s:
s += ",%s=:%s" % (param, param)
else:
s = "%s=:%s" % (param, param)
if id == '0':
query = "INSERT INTO tags (topic, tag, tag_name) VALUES ('{0}', '{1}', '{2}')".format(
new_values['topic'], new_values['tag'], new_values['tag_name'])
else:
new_values['id'] = id
query = "UPDATE tags SET %s WHERE id = :id;" % s
execute_query(request, query, new_values)
def update_topic(request, topic, new_values):
# formater les champs
s = ''
for param in new_values.keys():
if s:
s += ",%s=:%s" % (param, param)
else:
s = "%s=:%s" % (param, param)
if topic == '0':
query = "INSERT INTO topics (topic, topic_name, topic_quote) VALUES ('{0}', '{1}', '{2}')".format(
topic, new_values['topic_name'], new_values['topic_quote'])
else:
new_values['topic'] = topic
query = "UPDATE topics SET %s WHERE topic = :topic;" % s
execute_query(request, query, new_values)

View File

@@ -42,7 +42,6 @@ def update_user(request, name, new_values):
else: else:
s = "%s=:%s" % (param, param) s = "%s=:%s" % (param, param)
import pdb;pdb.set_trace()
if name == '0': if name == '0':
query = "INSERT INTO users (name, password) VALUES ('{0}', '{1}')".format(new_values['name'], new_values['password']) query = "INSERT INTO users (name, password) VALUES ('{0}', '{1}')".format(new_values['name'], new_values['password'])
else: else:
@@ -50,8 +49,8 @@ def update_user(request, name, new_values):
query = "UPDATE users SET %s WHERE name = :name;" % s query = "UPDATE users SET %s WHERE name = :name;" % s
execute_query(request, query, new_values) execute_query(request, query, new_values)
def update_last_connection(request, id): def update_last_connection(request, id, password_hash):
"""Update last connection for login """ """Update last connection for login """
last_logged = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') last_logged = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
query = "UPDATE users SET last_logged = '" + last_logged + "' WHERE id=:id;" query = "UPDATE users SET last_logged=:last_logged, password=:password_hash WHERE id=:id;"
execute_query(request, query, {'id': id}) execute_query(request, query, {'id': id, 'last_logged': last_logged, 'password_hash': password_hash})

View File

@@ -19,7 +19,7 @@
<hr/> <hr/>
<p> <p>
Auteur : <strong>{{ entry.author }}</strong><br> Auteur : <strong>{{ entry.author }}</strong><br>
Publié le : <strong>{{ entry.created.strftime("%d-%m-%Y - %H:%M") }}</strong><br> Publié le : <strong>{{ entry.create_date }}</strong><br>
{% if request.authenticated_userid %} {% if request.authenticated_userid %}
Topic - Tag : <strong>{{ entry.topic_id }}</strong> - <strong>{{ entry.tag }}</strong><br> Topic - Tag : <strong>{{ entry.topic_id }}</strong> - <strong>{{ entry.tag }}</strong><br>
Statut : <strong>{{ entry.status }}</strong> Statut : <strong>{{ entry.status }}</strong>

View File

@@ -4,46 +4,54 @@
<form action="{{ url }}" method="post" class="form"> <form action="{{ url }}" method="post" class="form">
{% for error in form.title.errors %} <div class="form-group">
<div class="error">{{ error }}</div> <label class="required-field" for="title">Titre</label>
<input class="form-control" name="title" type="text" value="{{entry.title}}" required>
</div>
<div class="form-group">
<label class="required-field" for="body">Corps du texte</label>
<textarea class="form-control monospace-font" id="body" name="body" required rows="20" cols="35">
{{ entry.body }}
</textarea>
</div>
<div class="form-group">
<label class="required-field" for="tag">Tag</label>
<select class="form-control" id="tag" name="tag" value="{{ entry.tag }}">
{% for x in tags %}
<option value="{{x.tag}}"
{% if entry.tag == x.tag %} selected {% endif %}>{{x.tag_name}}</option>
{% endfor %} {% endfor %}
<div class="form-group"> </select>
<label class="required-field" for="title">{{ form.title.label }}</label>
{{ form.title(class_='form-control') }}
</div>
{% for error in form.body.errors %}
<div class="error">{{ error }}</div>
{% endfor %}
<div class="form-group">
<label class="required-field" for="body">{{ form.body.label }}</label>
{{ form.body(class_='form-control monospace-font', cols="35", rows="20") }}
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="required-field" for="tag">{{ form.tag.label }}</label> <label class="required-field" for="author">Auteur}</label>
{{ form.tag(class_='form-control') }} <input class="form-control" name="author" type="text" value="{{entry.author}}" required>
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="required-field" for="author">{{ form.author.label }}</label> <label class="required-field" for="status">Statut</label>
{{ form.author(class_='form-control') }} <select class="form-control" id="status" name="status" value="{{ entry.status}}">
<option value="brouillon"
{% if entry.status == "brouillon" %} selected {% endif %}>Brouillon</option>
<option value="privé"
{% if entry.status == "privé" %} selected {% endif %}>Privé</option>
<option value="publié"
{% if entry.status == "publié" %} selected {% endif %}>Publié</option>
</select>
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="required-field" for="status">{{ form.status.label }}</label> <label class="required-field" for="created">Créé le</label>
{{ form.status(class_='form-control') }} <input class="form-control" name="created" type="text" value="{{entry.created}}" required>
</div>
<div class="form-group">
<label class="required-field" for="created">{{ form.created.label }}</label>
{{ form.created(class_='form-control') }}
</div> </div>
<p> <p>
Topic : <strong>{{ entry.topic_id }}</strong><br> Topic : <strong>{{ entry.topic_id }}</strong><br>
{% if blog_id != '0' %} {% if blog_id != '0' %}
Modifié le : <strong>{{ entry.edited.strftime("%d-%m-%Y - %H:%M") }}</strong> Modifié le : <strong>{{ entry.edit_date }}</strong>
{% endif %} {% endif %}
</p> </p>
<br /> <br />

View File

@@ -7,16 +7,13 @@
<div class="form-group"> <div class="form-group">
<div class="col-sm-offset-2 col-sm-8"> <div class="col-sm-offset-2 col-sm-8">
<div class="input-group" align="center"> <div class="input-group" align="center">
{{ form.criteria(class_='form-control') }} <input class="form-control" name="criteria" type="text" value="{{criteria}}" required>
<span class="input-group-btn"> <span class="input-group-btn">
<button id="submitButton" class="btn btn-primary" type="submit" name="form.submitted"> <button id="submitButton" class="btn btn-primary" type="submit" name="form.submitted">
Rechercher Rechercher
</button> </button>
</span> </span>
</div> </div>
{% for error in form.criteria.errors %}
<div class="text-danger">{{ error }}</div>
{% endfor %}
</div> </div>
</div> </div>
</form> </form>
@@ -35,12 +32,12 @@
{% for entry in items %} {% for entry in items %}
<tr> <tr>
<td> <td>
<a href="{{ request.route_url('blog', id=entry.id, slug=entry.slug) }}"> <a href="{{ request.route_url('blog', id=entry.id, slug='slug') }}">
{{ entry.title }} {{ entry.title }}
</a> </a>
</td> </td>
<td>{{ entry.tag }}</td> <td>{{ entry.tag }}</td>
<td>{{ entry.edited.strftime("%d-%m-%Y - %H:%M") }}</td> <td>{{ entry.edit_date }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>

View File

@@ -78,7 +78,7 @@
<tr> <tr>
<td>{{ entry.create_date }}</td> <td>{{ entry.create_date }}</td>
<td> <td>
<a href="{{ request.route_url('blog', id=entry.id, slug=entry.slug) }}">{{ entry.title }}</a> <a href="{{ request.route_url('blog', id=entry.id, slug='slug') }}">{{ entry.title }}</a>
</td> </td>
<td>{{ entry.author }}</td> <td>{{ entry.author }}</td>
{% if entry.status == 'brouillon' %} {% if entry.status == 'brouillon' %}

View File

@@ -43,7 +43,7 @@
<td>{{ entry.edit_date }}</td> <td>{{ entry.edit_date }}</td>
<td>{{ entry.editor }}</td> <td>{{ entry.editor }}</td>
<td> <td>
<a href="{{ request.route_url('blog', id=entry.id, slug=entry.slug) }}">{{ entry.title }}</a> <a href="{{ request.route_url('blog', id=entry.id, slug='slug') }}">{{ entry.title }}</a>
</td> </td>
<td>{{ entry.tag }}</td> <td>{{ entry.tag }}</td>
{% if entry.status == 'brouillon' %} {% if entry.status == 'brouillon' %}

View File

@@ -2,24 +2,16 @@
{% block content %} {% block content %}
<form action="{{ url }}" method="post" class="form"> <form action="{{ url }}" method="post" role="form">
{% for error in form.tag.errors %}
<div class="error">{{ error }}</div>
{% endfor %}
<div class="form-group"> <div class="form-group">
<label class="required-field" for="tag">{{form.tag.label}}</label> <label class="required-field" for="tag">Tag</label>
{{form.tag(class_='form-control')}} <input class="form-control" name="tag" type="text" value="{{entry.tag}}" required>
</div> </div>
{% for error in form.tag_name.errors %}
<div class="error">{{error}}</div>
{% endfor %}
<div class="form-group"> <div class="form-group">
<label class="required-field" for="tag_name">{{form.tag_name.label}}</label> <label class="required-field" for="tag_name">Intitulé</label>
{{form.tag_name(class_='form-control')}} <input class="form-control" name="tag_name" type="text" value="{{entry.tag_name}}" required>
</div> </div>
<div class="form-group"> <div class="form-group">
@@ -27,7 +19,7 @@
<span class="glyphicon glyphicon-chevron-left"></span> Retour</a> <span class="glyphicon glyphicon-chevron-left"></span> Retour</a>
<button class="btn btn-primary" type="submit" name="form.submitted"> <button class="btn btn-primary" type="submit" name="form.submitted">
<span class="glyphicon glyphicon-ok"></span> Enregistrer</button> <span class="glyphicon glyphicon-ok"></span> Enregistrer</button>
{% if form.id.data %} {% if entry.tag != '0' %}
<button class="btn btn-danger" type="button" data-toggle="modal" data-target="#confirmDelete"> <button class="btn btn-danger" type="button" data-toggle="modal" data-target="#confirmDelete">
<span class="glyphicon glyphicon-remove"></span> Supprimer</button> <span class="glyphicon glyphicon-remove"></span> Supprimer</button>
{% endif %} {% endif %}
@@ -46,7 +38,7 @@
</div> </div>
<div class="modal-body"> <div class="modal-body">
<!-- The form is placed inside the body of modal --> <!-- The form is placed inside the body of modal -->
<p>Etes-vous certain(e) de vouloir supprimer le Tag <b>{{ form.tag_name.data }}</b> ?</p> <p>Etes-vous certain(e) de vouloir supprimer le Tag <b>{{ tag_name }}</b> ?</p>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<div class="form-group"> <div class="form-group">

View File

@@ -2,32 +2,23 @@
{% block content %} {% block content %}
<form action="{{ url }}" method="post" class="form"> <form action="{{ url }}" method="post" role="form">
{% for error in form.topic.errors %}
<div class="error">{{ error }}</div>
{% endfor %}
<div class="form-group"> <div class="form-group">
<label class="required-field" for="topic">{{form.topic.label}}</label> <label class="required-field" for="topic">Topic</label>
{{form.topic(class_='form-control')}} <input class="form-control" name="topic" type="text" value="{{entry.topic}}" required>
</div> </div>
{% for error in form.topic_name.errors %}
<div class="error">{{error}}</div>
{% endfor %}
<div class="form-group"> <div class="form-group">
<label class="required-field" for="topic_name">{{form.topic_name.label}}</label> <label class="required-field" for="topic_name">Intitulé</label>
{{form.topic_name(class_='form-control')}} <input class="form-control" name="topic_name" type="text" value="{{entry.topic_name}}" required>
</div> </div>
{% for error in form.topic_quote.errors %}
<div class="error">{{ error }}</div>
{% endfor %}
<div class="form-group"> <div class="form-group">
<label class="required-field" for="topic_quote">{{ form.topic_quote.label }}</label> <label class="required-field" for="topic_quote">Citation</label>
{{ form.topic_quote(class_='form-control monospace-font', cols="35", rows="5") }} <textarea class="form-control monospace-font" id="topic_quote" name="topic_quote" required rows="10" cols="35">
{{ entry.topic_quote }}
</textarea>
</div> </div>
<div class="form-group"> <div class="form-group">
@@ -35,17 +26,16 @@
<span class="glyphicon glyphicon-chevron-left"></span> Retour</a> <span class="glyphicon glyphicon-chevron-left"></span> Retour</a>
<button class="btn btn-primary" type="submit" name="form.submitted"> <button class="btn btn-primary" type="submit" name="form.submitted">
<span class="glyphicon glyphicon-ok"></span> Enregistrer</button> <span class="glyphicon glyphicon-ok"></span> Enregistrer</button>
{% if form.topic.data %} {% if entry.topic != '0' %}
<button class="btn btn-danger" type="button" data-toggle="modal" data-target="#confirmDelete"> <button class="btn btn-danger" type="button" data-toggle="modal" data-target="#confirmDelete">
<span class="glyphicon glyphicon-remove"></span> Supprimer</button> <span class="glyphicon glyphicon-remove"></span> Supprimer</button>
{% endif %} {% endif %}
</div> </div>
</form> </form>
<h3>Liste des Tags</h3> <h3>Liste des Tags</h3>
<p><a href="{{ request.route_url('tag_edit', topic=form.topic.data, id='0') }}" class="btn btn-success" role="button"> <p><a href="{{ request.route_url('tag_edit', topic=entry.topic, id='0') }}" class="btn btn-success" role="button">
<span class="glyphicon glyphicon-plus"></span> Nouveau</a> <span class="glyphicon glyphicon-plus"></span> Nouveau</a>
</p> </p>
@@ -60,7 +50,7 @@
<tr> <tr>
<td>{{ entry.tag }}</td> <td>{{ entry.tag }}</td>
<td> <td>
<a href="{{ request.route_url('tag_edit', topic=form.topic.data, id=entry.id) }}"> <a href="{{ request.route_url('tag_edit', topic=entry.topic, id=entry.id) }}">
{{ entry.tag_name }} {{ entry.tag_name }}
</a> </a>
</td> </td>
@@ -78,7 +68,7 @@
</div> </div>
<div class="modal-body"> <div class="modal-body">
<!-- The form is placed inside the body of modal --> <!-- The form is placed inside the body of modal -->
<p>Etes-vous certain(e) de vouloir supprimer le Topic <b>{{ form.topic_name.data }}</b> ?</p> <p>Etes-vous certain(e) de vouloir supprimer le Topic <b>{{ entry.topic_name }}</b> ?</p>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<div class="form-group"> <div class="form-group">

View File

@@ -4,7 +4,8 @@ import markdown
import datetime #<- will be used to set default dates on models import datetime #<- will be used to set default dates on models
from ..models.entries import * from ..models.entries import *
from ..forms import BlogCreateForm, BlogUpdateForm, BlogSearchForm from webhelpers2.text import urlify #<- will generate slugs
from webhelpers2.date import distance_of_time_in_words #<- human friendly dates
@view_config(route_name='blog', renderer='cao_sunyata:templates/blog.jinja2') @view_config(route_name='blog', renderer='cao_sunyata:templates/blog.jinja2')
@@ -41,16 +42,19 @@ def blog_copy(request):
return HTTPFound(location=request.route_url('topic', topic=topic)) return HTTPFound(location=request.route_url('topic', topic=topic))
# create a new post # create a new post
dup_entry = BlogRecord() new_values = {}
dup_entry.title = entry.title + ' - copie' new_values['title'] = entry.title + ' - copie'
dup_entry.body = entry.body new_values['body'] = entry.body
dup_entry.topic_id = entry.topic_id new_values['created'] = datetime.datetime.now()
dup_entry.tag = entry.tag new_values['edited'] = datetime.datetime.now()
dup_entry.author = entry.author new_values['topic_id'] = topic
dup_entry.status = 'brouillon' new_values['tag'] = entry.tag
dup_entry.created = datetime.datetime.now() new_values['author'] = entry.author
dup_entry.edited = datetime.datetime.now() new_values['status'] = 'brouillon'
request.dbsession.add(dup_entry) new_values['creator'] = request.authenticated_userid
new_values['editor'] = ''
update_entry(request, '0', new_values)
return HTTPFound(location=request.route_url('topic', topic=topic))
request.session.flash("La page a été duppliquée avec succès", 'success') request.session.flash("La page a été duppliquée avec succès", 'success')
return HTTPFound(location=request.route_url('topic', topic=topic)) return HTTPFound(location=request.route_url('topic', topic=topic))
@@ -68,11 +72,17 @@ def blog_edit(request):
if blog_id == '0': if blog_id == '0':
# create a new post # create a new post
entry = BlogRecord() entry = {}
entry.topic_id = topic entry['title'] = ''
entry.created = datetime.datetime.now() entry['body'] = ''
form = BlogCreateForm(request.POST, entry) entry['created'] = datetime.datetime.now()
form.tag.choices = [(row.tag, row.tag_name) for row in tags] entry['edited'] = datetime.datetime.now()
entry['topic_id'] = topic
entry['tag'] = ''
entry['author'] = ''
entry['status'] = ''
entry['creator'] = request.authenticated_userid
entry['editor'] = ''
page_title = 'Nouvelle page' page_title = 'Nouvelle page'
else: else:
@@ -81,41 +91,37 @@ def blog_edit(request):
if not entry: if not entry:
request.session.flash("Page non trouvée : %s" % blog_id, 'warning') request.session.flash("Page non trouvée : %s" % blog_id, 'warning')
return HTTPFound(location=request.route_url('topic', topic=topic)) return HTTPFound(location=request.route_url('topic', topic=topic))
form = BlogUpdateForm(request.POST, entry)
form.tag.choices = [(row.tag, row.tag_name) for row in tags]
page_title = 'Modifier : ' + entry.title page_title = 'Modifier : ' + entry.title
if 'form.submitted' in request.params and form.validate(): if 'form.submitted' in request.params:
if blog_id == '0': new_values = {}
form.populate_obj(entry) for param in entry.keys():
entry.topic_id = topic if param in request.params and request.params[param] != entry[param]:
new_values[param] = request.params[param]
if param == 'title':
# interdire le car '/' dans le titre à cause du slug # interdire le car '/' dans le titre à cause du slug
entry.title = entry.title.replace('/','.') new_values['title'] = new_values['title'].replace('/','.')
entry.creator = request.authenticated_userid elif param == 'body':
entry.editor = entry.creator new_values['body'] = new_values['body'].strip()
request.dbsession.add(entry)
# import pdb;pdb.set_trace()
if new_values:
new_values['topic_id'] = topic
new_values['editor'] = request.authenticated_userid
update_entry(request, blog_id, new_values)
return HTTPFound(location=request.route_url('topic', topic=topic)) return HTTPFound(location=request.route_url('topic', topic=topic))
else:
del form.id # SECURITY: prevent overwriting of primary key
form.populate_obj(entry)
# interdire le car '/' dans le titre à cause du slug
entry.title = entry.title.replace('/','.')
entry.edited = datetime.datetime.now()
entry.editor = request.authenticated_userid
return HTTPFound(location=request.route_url('blog', id=entry.id, slug=entry.slug))
if 'form.deleted' in request.params: if 'form.deleted' in request.params:
BlogRecordService.delete(request, blog_id) delete_entry(request, blog_id)
request.session.flash("La page a été supprimée avec succès.", 'success') request.session.flash("La page a été supprimée avec succès.", 'success')
return HTTPFound(location=request.route_url('topic', topic=topic)) return HTTPFound(location=request.route_url('topic', topic=topic))
return { return {
'page_title': page_title, 'page_title': page_title,
'url': url, 'url': url,
'form': form,
'blog_id': blog_id, 'blog_id': blog_id,
'entry': entry, 'entry': entry,
'tags': tags,
} }
@@ -127,14 +133,14 @@ def blog_search(request):
# generate a list of all tags of all topics # generate a list of all tags of all topics
if request.authenticated_userid: if request.authenticated_userid:
# get all topics # get all topics
topics = BlogRecordService.get_topics(request) topics = get_topics(request)
for topic in topics: for topic in topics:
liste += '<h4><a href="{0}">{1}</a></h4>'.format( liste += '<h4><a href="{0}">{1}</a></h4>'.format(
request.route_url('topic', topic=topic.topic), topic.topic_name) request.route_url('topic', topic=topic.topic), topic.topic_name)
# get all the tags of the topic # get all the tags of the topic
tags = BlogRecordService.get_tags_byTopic(request, topic.topic) tags = get_tags_byTopic(request, topic.topic)
if tags: if tags:
liste += '<ul>' liste += '<ul>'
for tag in tags: for tag in tags:
@@ -143,16 +149,14 @@ def blog_search(request):
tag.tag_name, count) tag.tag_name, count)
liste += '</ul>' liste += '</ul>'
form = BlogSearchForm(request.POST)
items = [] items = []
if 'form.submitted' in request.params and form.validate(): if 'form.submitted' in request.params:
criteria = request.params['criteria'] criteria = request.params['criteria']
# si afficher tous les fiches ? # si afficher tous les fiches ?
items = get_entries_by_criteria(request, criteria) items = get_entries_by_criteria(request, criteria)
return { return {
'page_title': "Rechercher", 'page_title': "Rechercher",
'form': form,
'items': items, 'items': items,
'criteria': criteria, 'criteria': criteria,
'liste': liste, 'liste': liste,
@@ -164,14 +168,14 @@ def topic(request):
topic = request.matchdict['topic'] topic = request.matchdict['topic']
# get the topic record # get the topic record
topic_record = BlogRecordService.get_topic_byTopic(request, topic) topic_record = get_topic_byTopic(request, topic)
# convertir champ topic_quote en HTML # convertir champ topic_quote en HTML
topic_quote = markdown.markdown(topic_record.topic_quote) topic_quote = markdown.markdown(topic_record.topic_quote)
# insèrer le path de static/img # insèrer le path de static/img
topic_quote = topic_quote.replace('static/', "%s/static/" % request.application_url) topic_quote = topic_quote.replace('static/', "%s/static/" % request.application_url)
# get all the tags of this topic # get all the tags of this topic
tags = BlogRecordService.get_tags_byTopic(request, topic) tags = get_tags_byTopic(request, topic)
# generate the items list group by tag # generate the items list group by tag
liste = '' liste = ''
@@ -182,10 +186,11 @@ def topic(request):
if items: if items:
liste += '<ul><table class="table table-condensed">' liste += '<ul><table class="table table-condensed">'
for item in items: for item in items:
item_slug = urlify(item.title)
liste += '<tr>' liste += '<tr>'
liste += '<td><a href="%s">%s</a></td>' % (request.route_url('blog', id=item.id, slug=item.slug), item.title) liste += '<td><a href="%s">%s</a></td>' % (request.route_url('blog', id=item.id, slug=item_slug), item.title)
liste += '<td>%s</td>' % item.author liste += '<td>%s</td>' % item.author
liste += '<td>%s</td>' % item.created.strftime("%d-%m-%Y") liste += '<td>%s</td>' % item.create_date
if item.status != 'publié': if item.status != 'publié':
liste += '<td><span class="label label-danger">%s</span></td>' % item.status liste += '<td><span class="label label-danger">%s</span></td>' % item.status
liste += '</tr>' liste += '</tr>'

View File

@@ -7,7 +7,6 @@ from pyramid.httpexceptions import HTTPFound
from pyramid.security import remember, forget from pyramid.security import remember, forget
from pyramid_mailer.message import Message, Attachment from pyramid_mailer.message import Message, Attachment
from ..forms import UserCreateForm, TopicForm, TagForm
from ..models.users import * from ..models.users import *
from ..models.entries import * from ..models.entries import *
from datetime import datetime from datetime import datetime
@@ -161,9 +160,15 @@ def login(request):
user = get_users_by_name(request, username) user = get_users_by_name(request, username)
# Is user existed ? # Is user existed ?
if user : if user :
if blogger_pwd_context.verify(userpwd, user.password): # is it cleartext?
if userpwd == user.password:
password_hash = blogger_pwd_context.encrypt(user.password)
else:
password_hash = user.password
if blogger_pwd_context.verify(userpwd, password_hash):
# pwd OK, set last login date # pwd OK, set last login date
update_last_connection(request, user.id) update_last_connection(request, user.id, password_hash)
# force le commit car il ne se fait pas automatiquement après l'update # force le commit car il ne se fait pas automatiquement après l'update
transaction.commit() transaction.commit()
headers = remember(request, username) headers = remember(request, username)
@@ -240,7 +245,6 @@ def user_edit(request):
if 'form.deleted' in request.params: if 'form.deleted' in request.params:
import pdb;pdb.set_trace()
delete_user(request, user.id) delete_user(request, user.id)
request.session.flash("La fiche a été supprimée avec succès.", 'success') request.session.flash("La fiche a été supprimée avec succès.", 'success')
return HTTPFound(location=url_retour) return HTTPFound(location=url_retour)
@@ -264,8 +268,7 @@ def topics(request):
'topics': topics 'topics': topics
} }
@view_config(route_name='topic_edit', @view_config(route_name='topic_edit', renderer='cao_sunyata:templates/topic_edit.jinja2', permission='view')
renderer='cao_sunyata:templates/topic_edit.jinja2', permission='view')
def topic_edit(request): def topic_edit(request):
# get topic parameters from request # get topic parameters from request
topic = request.matchdict['topic'] topic = request.matchdict['topic']
@@ -276,44 +279,43 @@ def topic_edit(request):
if topic == '0': if topic == '0':
# create a new topic # create a new topic
entry = Topics() entry = {}
form = TopicForm(request.POST, entry) entry['topic'] = ''
page_title = "Nouveau Topic" entry['topic_name'] = ''
entry['topic_quote'] = ''
page_title = "Nouveau topic"
else: else:
# modify post # modify post
entry = get_topic_byTopic(request, topic) entry = get_topic_byTopic(request, topic)
if not entry: if not entry:
request.session.flash(u"Topic non trouvé : %s" % topic, 'warning') request.session.flash(u"Topic non trouvé : %s" % topic, 'warning')
return HTTPFound(location=request.route_url('topics')) return HTTPFound(location=request.route_url('topics'))
form = TopicForm(request.POST, entry)
page_title = entry.topic_name page_title = entry.topic_name
if 'form.submitted' in request.params and form.validate(): if 'form.submitted' in request.params:
if topic == '0': new_values = {}
form.populate_obj(entry) for param in entry.keys():
request.dbsession.add(entry) if param in request.params and request.params[param] != entry[param]:
new_values[param] = request.params[param]
return HTTPFound(location=request.route_url('topics')) if new_values:
else: update_topic(request, topic, new_values)
del form.topic # SECURITY: prevent overwriting of primary key request.session.flash(u"La fiche a été mise à jour avec succès.", 'success')
form.populate_obj(entry)
return HTTPFound(location=request.route_url('topics')) return HTTPFound(location=request.route_url('topics'))
if 'form.deleted' in request.params: if 'form.deleted' in request.params:
topic_delete(request, entry.topic) delete_topic(request, entry.topic)
request.session.flash("La fiche a été supprimée avec succès.", 'success') request.session.flash("La fiche a été supprimée avec succès.", 'success')
return HTTPFound(location=request.route_url('topics')) return HTTPFound(location=request.route_url('topics'))
return { return {
'page_title': page_title, 'page_title': page_title,
'url': url, 'url': url,
'form': form, 'entry': entry,
'tags': tags, 'tags': tags,
} }
@view_config(route_name='tag_edit', @view_config(route_name='tag_edit', renderer='cao_sunyata:templates/tag_edit.jinja2', permission='view')
renderer='cao_sunyata:templates/tag_edit.jinja2', permission='view')
def tag_edit(request): def tag_edit(request):
# get tag parameters from request # get tag parameters from request
topic = request.matchdict['topic'] topic = request.matchdict['topic']
@@ -322,39 +324,41 @@ def tag_edit(request):
if tag_id == '0': if tag_id == '0':
# create a new tag # create a new tag
entry = Tags() entry = {}
form = TagForm(request.POST, entry) entry['topic'] = ''
entry['tag'] = ''
entry['tag_name'] = ''
page_title = "Nouveau Tag" page_title = "Nouveau Tag"
else: else:
# modify post # modify post
entry = get_tags_byId(request, tag_id) entry = get_tags_byId(request, tag_id)
if not entry: if not entry:
request.session.flash(u"Tag non trouvé : %s" % tag_id, 'warning') request.session.flash(u"Tag non trouvé : %s" % tag_id, 'warning')
return HTTPFound(location=request.route_url('topic_edit', topic=topic)) return HTTPFound(location=request.route_url('topic_edit', topic=topic))
form = TagForm(request.POST, entry)
page_title = entry.tag_name page_title = entry.tag_name
if 'form.submitted' in request.params and form.validate(): if 'form.submitted' in request.params :
if tag_id == '0': new_values = {}
form.populate_obj(entry) for param in entry.keys():
entry.topic = topic if param in request.params and request.params[param] != entry[param]:
request.dbsession.add(entry) new_values[param] = request.params[param]
return HTTPFound(location=request.route_url('topic_edit', topic=topic))
else: # import pdb;pdb.set_trace()
del form.id # SECURITY: prevent overwriting of primary key if new_values:
form.populate_obj(entry) new_values['topic'] = topic
update_tag(request, tag_id, new_values)
request.session.flash(u"La fiche a été mise à jour avec succès.", 'success')
return HTTPFound(location=request.route_url('topic_edit', topic=topic)) return HTTPFound(location=request.route_url('topic_edit', topic=topic))
if 'form.deleted' in request.params: if 'form.deleted' in request.params:
tag_delete(request, entry.id) delete_tag(request, tag_id)
request.session.flash("La fiche a été supprimée avec succès.", 'success') request.session.flash("La fiche a été supprimée avec succès.", 'success')
return HTTPFound(location=request.route_url('topic_edit', topic=topic)) return HTTPFound(location=request.route_url('topic_edit', topic=topic))
return { return {
'page_title': page_title, 'page_title': page_title,
'url': url, 'url': url,
'form': form, 'entry': entry,
'topic': topic, 'topic': topic,
} }

View File

@@ -21,7 +21,6 @@ requires = [
'SQLAlchemy==1.4.54', 'SQLAlchemy==1.4.54',
'transaction', 'transaction',
'zope.sqlalchemy==2.0', 'zope.sqlalchemy==2.0',
'wtforms', # form library
'webhelpers2', # various web building related helpers 'webhelpers2', # various web building related helpers
'passlib', 'passlib',
'python-magic', 'python-magic',