Created
November 15, 2013 06:42
-
-
Save cldershem/7480140 to your computer and use it in GitHub Desktop.
Flask/WTForms/Jinja2 tag list headaches.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask.ext.wtf import Form, RecaptchaField | |
from wtforms import (TextField, TextAreaField, PasswordField, | |
SubmitField, BooleanField) | |
from wtforms.validators import Email, EqualTo, Required | |
from models import User, Post, Page, Unity | |
from mongoengine.queryset import DoesNotExist | |
from utils import makeSlug, TagListField | |
from flask.ext.pagedown.fields import PageDownField | |
class UnityForm(Form): | |
title = TextField("Title", [Required( | |
"Please enter a title for your post.")]) | |
body = PageDownField("Body", [Required( | |
"Please enter a body to your post.")]) | |
tags = TagListField("Tags") | |
source = TagListField("Source") | |
isDraft = BooleanField("Save as draft?") | |
isBlogPost = BooleanField("Publish to blog?") | |
submit = SubmitField("Submit") | |
def __init__(self, *args, **kwargs): | |
Form.__init__(self, *args, **kwargs) | |
def validate(self): | |
if not Form.validate(self): | |
return False | |
else: | |
return True | |
def validate_with_slug(self): | |
if self.validate(): | |
try: | |
newSlug = makeSlug(self.title.data) | |
slug = Unity.objects.get(slug=newSlug) | |
if slug: | |
self.title.errors.append("That title already exists.") | |
return False | |
except DoesNotExist: | |
return True |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import url_for | |
from app import db, bcrypt | |
from app.constants import DATE_TIME_NOW | |
class Unity(db.Document): | |
created_at = db.DateTimeField(default=DATE_TIME_NOW, required=True) | |
edited_on = db.ListField(db.DateTimeField(default=DATE_TIME_NOW)) | |
title = db.StringField(max_length=255, required=True) | |
slug = db.StringField(max_length=255, required=True) | |
author = db.ReferenceField(User) | |
body = db.StringField(required=True) | |
tags = db.ListField(db.StringField(max_length=50)) | |
source = db.ListField(db.StringField(max_length=255)) | |
isDraft = db.BooleanField(default=True) | |
isBlogPost = db.BooleanField(default=False) | |
comments = db.ListField(db.EmbeddedDocumentField(Comment)) | |
def get_absolute_url(self): | |
return url_for('unity', kwargs={"slug": self.slug}) | |
def __unicode__(self): | |
return self.title | |
meta = {'allow_inheritance': True, | |
'indexes': ['-created_at', 'slug'], | |
'ordering': ['-created_at']} | |
def __repr__(self): | |
return '<Unity %r, -%r>' % (self.slug, self.author) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- extends base.html --> | |
{% extends "base.html" %} | |
{% from "macros.html" import render_form with context %} | |
{% from "macros.html" import render_comments with context %} | |
{% block content %} | |
{{unity.body|markRight}} | |
<hr> | |
<div id="postmeta"> | |
<p> | |
by <strong><a href="{{ url_for('users.profile', user_id=unity.author.email) }}">{{ unity.author.email }}</a></strong> | |
<span id="pipeseparator"> | </span>posted {{ unity.created_at.strftime('%H:%M %Y-%m-%d') }} | |
{% if unity.edited_on|length > 1 %} | |
<span id="pipeseparator"> | </span>edited {{ unity.edited_on[-1].strftime('%H:%M %Y-%m-%d') }} | |
{% endif %} | |
</p> | |
{% if unity.tags %} | |
<p> | |
<strong>tags: </strong> | |
{% for tag in unity.tags %} | |
[<a class="unitytags" href="{{ url_for('unity.listUnity', tag=tag) }}">{{tag}}</a>] | |
{% endfor %} | |
</p> | |
{% endif %} | |
{% if unity.source %} | |
<p> | |
<strong>source: </strong> | |
{% for source in unity.source %} | |
[<a href="{{ source }}">{{ source }}</a>] | |
{% endfor %} | |
</p> | |
{% endif %} | |
{% if current_user.is_authenticated() == True %} | |
<p> | |
<a href="{{url_for('unity.editUnity', slug=unity.slug)}}">edit page</a> | |
</p> | |
{% endif %} | |
</div><!--end postmeta--> | |
{{render_comments(unity.comments)}} | |
{% endblock %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from unicodedata import normalize | |
import re | |
from config import SECRET_KEY | |
from itsdangerous import (URLSafeSerializer, BadSignature, | |
URLSafeTimedSerializer, SignatureExpired) | |
from jinja2 import Markup | |
from markdown import markdown | |
from app import app | |
from wtforms.fields import Field | |
from wtforms.widgets import TextInput | |
class TagListField(Field): | |
widget = TextInput() | |
def _value(self): | |
"""values on load""" | |
if self.data: | |
return u', '.join(self.data) | |
else: | |
return u'' | |
def process_formdata(self, valuelist): | |
if valuelist: | |
self.data = [x.strip() for x in valuelist[0].split(',')] | |
else: | |
self.data = [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import (Blueprint, render_template, flash, request, | |
redirect, url_for) | |
from jinja2 import TemplateNotFound | |
from app.models import Unity, User, Comment | |
from app.forms import UnityForm, CommentForm | |
from app.constants import DATE_TIME_NOW | |
from app.utils import makeSlug | |
from flask.ext.login import login_required, current_user | |
from flask.ext.mongoengine import Pagination | |
mod = Blueprint('unity', __name__, url_prefix='/unity') | |
@mod.route('/<slug>/edit', methods=['GET', 'POST']) | |
@login_required | |
def editUnity(slug): | |
unity = Unity.objects.get(slug=slug) | |
slug = unity.slug | |
form = UnityForm(obj=unity) | |
def validate_on_update(): | |
if slug == makeSlug(form.title.data): | |
return form.validate() | |
else: | |
return form.validate_with_slug() | |
if request.method == 'POST': | |
if not validate_on_update(): | |
return render_template('unity/newUnity.html', | |
title=unity.title, | |
slug=slug, | |
form=form) | |
else: | |
form.populate_obj(unity) | |
unity.edited_on.append(DATE_TIME_NOW) | |
unity.save() | |
flash("Your page has been updated.") | |
return redirect(url_for('.staticUnity', slug=slug)) | |
elif request.method == 'GET': | |
form.populate_obj(unity) | |
return render_template('unity/newUnity.html', | |
pageTitle=unity.title, | |
slug=slug, | |
form=form) | |
@mod.route('/<slug>', methods=['GET', 'POST']) | |
def staticUnity(slug): | |
if request.method == 'POST': | |
unity = Unity.objects.get_or_404(slug=slug) | |
form = CommentForm() | |
if not form.validate(): | |
return render_template('unity/staticUnity.html', | |
pageTitle=unity.title, | |
unity=unity, | |
form=form) | |
else: | |
newComment = Comment(body=form.comment.data) | |
newComment.author = User.objects.get(email=current_user.email) | |
unity.comments.append(newComment) | |
unity.save() | |
form.comment.data = None # resets field on refresh | |
flash('Comment Posted') | |
return render_template('unity/staticUnity.html', | |
pageTitle=unity.title, | |
unity=unity, | |
form=form) | |
elif request.method == 'GET': | |
try: | |
return render_template('unity/%s.html' % slug, | |
pageTitle=slug) | |
except TemplateNotFound: | |
unity = Unity.objects.get_or_404(slug=slug) | |
form = CommentForm() | |
return render_template('unity/staticUnity.html', | |
pageTitle=unity.title, | |
unity=unity, | |
form=form) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment