Skip to content

Instantly share code, notes, and snippets.

@chriskief
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriskief/11191566 to your computer and use it in GitHub Desktop.
Save chriskief/11191566 to your computer and use it in GitHub Desktop.
from django.core.urlresolvers import reverse_lazy
from django.views.generic import CreateView
from app.forms import MyModelForm
from app.lib.api import API
class MyCreateView(CreateView):
template_name = 'form.html'
form_class = MyModelForm
success_url = reverse_lazy('home')
object = None
# allow data to be passed to this
# pulled from django/views/generic/edit.py/ModelFormMixin
def get_form_kwargs(self, data=None):
kwargs = super(MyCreateView, self).get_form_kwargs()
# if we have data, set the form's data so that we can auto-submit this form (without POSTing)
if data:
kwargs.update({'initial': data, 'data': data})
return kwargs
def get(self, request, *args, **kwargs):
# grab the data from the API
data = API.get_data()
formdata = {'user_id': data['user_id'],
'email': data['email'],
'first_name': data['first_name'],
'last_name': data['last_name']}
form_class = self.get_form_class()
# must instantiate the class directly and include the data object rather than use get_form
# will set both the initial and instance data
#form = self.get_form(form_class)
form = form_class(**self.get_form_kwargs(formdata))
# do we have a valid form submission
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
# once the user submits the form, validate the form and create the new user
def post(self, request, *args, **kwargs):
# setup the form
# we can use get_form this time as we no longer need to set the data property
form_class = self.get_form_class()
form = self.get_form(form_class)
# grab the data from the API
data = API.get_data()
form.initial = {'user_id': data['user_id'],
'email': data['email'],
'first_name': data['first_name'],
'last_name': data['last_name']}
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment