Created
August 23, 2012 14:19
-
-
Save techniq/3437077 to your computer and use it in GitHub Desktop.
FormView
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 google.appengine.ext import db | |
from flask import flash, url_for, redirect, request | |
from flask.views import View | |
from flaskext.wtf import Form | |
from wtforms.ext.appengine.db import model_form | |
from application.decorators import templated | |
class FormView(View): | |
methods = ['GET', 'POST'] | |
model_class = None | |
redirect_endpoint = None | |
def get_model(self): | |
return self.model_class.get(self.key) if self.key else None | |
def get_form(self): | |
ModelForm = model_form(self.model_class, Form) | |
return ModelForm(request.form, self.get_model()) | |
def get_fields(self): | |
return dict([(field.name, field.data) for field in self.get_form()]) | |
@templated() | |
def dispatch_request(self, key=None): | |
self.key = key | |
form = self.get_form() | |
model = self.get_model() | |
if form.validate_on_submit(): | |
if model: | |
# Update existing model from form fields | |
form.populate_obj(model) | |
flash("%s updated" % self.model_class.__name__) | |
else: | |
# Create new model from form fields | |
fields = self.get_fields() | |
model = self.model_class(**fields) | |
flash("%s added" % self.model_class.__name__) | |
model.put() | |
return redirect(url_for(self.redirect_endpoint)) | |
return {'form': form, 'key': key} |
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
class LocationView(FormView): | |
model_class = Location | |
redirect_endpoint = ".health_department" | |
def get_form(self): | |
ModelForm = model_form(Location, Form, exclude=['health_department']) | |
return ModelForm(request.form, self.get_model()) | |
def get_fields(self): | |
fields = super(LocationView, self).get_fields() | |
fields['health_department'] = HealthDepartment.get_by_key_name('site') | |
return fields |
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
class RestaurantView(FormView): | |
model_class = Restaurant | |
redirect_endpoint = "inspections" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment