Skip to content

Commit

Permalink
Added the ability to set the form action to any named URL\n Added the…
Browse files Browse the repository at this point in the history
… ability to set the form method to GET or POST - defaults to POST\nAdded new test page to support these two actions
  • Loading branch information
pydanny committed Aug 13, 2009
1 parent c5bcbbb commit 6f670e7
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 7 deletions.
28 changes: 28 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,34 @@ Using the django-uni-form templatetag in your form class (Intermediate)
{% with form.helper as helper %}
{% uni_form form helper %}
{% endwith %}
Using the django-uni-form templatetag to change action/method (Intermediate)
============================================================================
1. In your form class add the following after field definitions::

from uni_form.helpers import FormHelper, Submit

class MyForm(forms.Form):
title = forms.CharField(label=_("Title"), max_length=30, widget=forms.TextInput())

# Attach a formHelper to your forms class.
helper = FormHelper()
# Change the form and method
helper.form_action = 'my-url-name-defined-in-url-conf'
helper.form_method = 'GET' # Only GET and POST are legal
# add in a submit and reset button
submit = Submit('search','search this site')
helper.add_input(submit)
2. In your template do the following::

{% load uni_form %}
{% with form.helper as helper %}
{% uni_form form helper %}
{% endwith %}



Adding a layout to your form class (Intermediate)
Expand Down
54 changes: 51 additions & 3 deletions uni_form/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,22 @@
elements, and UI elements to forms generated via the uni_form template tag.
"""
from uni_form.util import BaseInput, Toggle
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
from django.core.urlresolvers import reverse, NoReverseMatch
from django.forms.forms import BoundField
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe


from uni_form.util import BaseInput, Toggle


class FormHelpersException(Exception):
""" This is raised when building a form via helpers throws an error.
We want to catch form helper errors as soon as possible because
debugging templatetags is never fun.
"""
pass


class Submit(BaseInput):
"""
Expand Down Expand Up @@ -189,12 +201,44 @@ class FormHelper(object):
"""

def __init__(self):
self._form_method = 'POST'
self._form_action = ''
self.form_id = ''
self.form_class = ''
self.inputs = []
self.toggle = Toggle()
self.layout = None

def get_form_method(self):
return self._form_method

def set_form_method(self, method):
if method.lower() not in ('get','post'):
raise FormHelpersException('Only GET and POST are valid in the \
form_method helper attribute')

self._form_method = method.upper()

# we set properties the old way because we want to support pre-2.6 python
form_method = property(get_form_method, set_form_method)

def get_form_action(self):
return self._form_action

def set_form_action(self, action):
try:
self._form_action = reverse(action)
except NoReverseMatch, e:
msg = 'Your form action needs to be a named url defined in a urlconf file\n'
msg += 'Your broken action is: %s\n' % action
msg += 'NoReverseMatch: %s' % e
raise FormHelpersException(msg)



# we set properties the old way because we want to support pre-2.6 python
form_action = property(get_form_action, set_form_action)

def add_input(self, input_object):
self.inputs.append(input_object)

Expand All @@ -206,6 +250,10 @@ def render_layout(self, form):

def get_attr(self):
items = {}
items['form_method'] = self.form_method.strip()

if self.form_action:
items['form_action'] = self.form_action.strip()
if self.form_id:
items['id'] = self.form_id.strip()
if self.form_class:
Expand Down
2 changes: 1 addition & 1 deletion uni_form/templates/uni_form/whole_uni_form.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{% load uni_form i18n %}

<form action="" class="uniForm {{ form_class }}" method="post" id="{{ form_id|slugify }}" {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>
<form action="{{ form_action }}" class="uniForm {{ form_class }}" method="{{ form_method }}" id="{{ form_id|slugify }}" {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>
{% if form_html %}{{ form_html }}{% else %}
<fieldset class="inlineLabels">
<legend>* {% trans "Required fields" %}</legend>
Expand Down
12 changes: 12 additions & 0 deletions uni_form/templatetags/uni_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ def get_render(self, context):
inputs = []
toggle_fields = set(())
if attrs:
form_method = attrs.get("form_method", 'POST')
form_action = attrs.get("form_action", '')
form_class = attrs.get("form_class", '')
form_id = attrs.get("id", "")
inputs = attrs.get('inputs', [])
Expand All @@ -90,6 +92,8 @@ def get_render(self, context):
response_dict = {
'form':actual_form,
'form_html':form_html,
'form_action':form_action,
'form_method':form_method,
'attrs':attrs,
'form_class' : form_class,
'form_id' : form_id,
Expand Down Expand Up @@ -119,6 +123,14 @@ def do_uni_form(parser, token):
attrs (optional): A string of semi-colon seperated attributes that can be
applied to theform in string format. They are used as follows.
form_action: applied to the form action attribute. Must be a named url in your urlconf that can be executed via the *url* default template tag. Defaults to empty::
form_action=<my-form-action>
form_method: applied to the form action attribute. Defaults to POST and the only available thing you can enter is GET.::
form_method=<my-form-method>
id: applied to the form as a whole. Defaults to empty::
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
<a href="{% url test_index %}">Basic test</a> |
<a href="{% url form_helper %}">Form Helper test</a> |
<a href="{% url view_helper %}">View Helper test</a> |
<a href="{% url layout_test %}">Layout test</a>
<a href="{% url layout_test %}">Layout test</a> |
<a href="{% url set_action_test %}">Set action test</a>
</p>
{% block body %}
{% endblock %}
Expand Down
2 changes: 2 additions & 0 deletions uni_form/tests/test_project/test_app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@


urlpatterns = patterns('',

url(r'^view_helper/$', "test_app.views.view_helper", name='view_helper'),
url(r'^form_helper/$', "test_app.views.form_helper", name='form_helper'),
url(r'^layout_test/$', "test_app.views.layout_test", name='layout_test'),
url(r'^view_helper_set_action/$', "test_app.views.view_helper_set_action", name='set_action_test'),


)
31 changes: 29 additions & 2 deletions uni_form/tests/test_project/test_app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.shortcuts import render_to_response
from django.template import RequestContext

from uni_form.helpers import FormHelper, Submit, Reset
from uni_form.helpers import FormHelper, Submit, Reset, Hidden

from test_app.forms import TestForm, HelperTestForm, LayoutTestForm

Expand Down Expand Up @@ -35,13 +35,40 @@ def view_helper(request):
helper.add_input(submit)
reset = Reset('reset','reset button')
helper.add_input(reset)
hidden = Hidden('not-seen','hidden value stored here')
helper.add_input(hidden)


# create the response dictionary
response_dictionary = {'form':form, 'helper': helper}

return render_to_response('test_app/view_helper.html',
response_dictionary,
context_instance=RequestContext(request))
context_instance=RequestContext(request))

def view_helper_set_action(request):

# Create the form
form = TestForm()

# create a formHelper
helper = FormHelper()

# add in a submit and reset button
submit = Submit('send-away','Send to other page')
helper.add_input(submit)

helper.form_action = 'view_helper'
helper.form_method = 'GET'

# create the response dictionary
response_dictionary = {'form':form, 'helper': helper}

return render_to_response('test_app/view_helper.html',
response_dictionary,
context_instance=RequestContext(request))



def form_helper(request):
if request.method == "POST":
Expand Down

0 comments on commit 6f670e7

Please sign in to comment.