This is what I am doing at the moment:
views.py
def activation_signupcount(request):
if request.method == 'POST':
return render_to_response('activation_signupcount.html',
{ 'datestart': request.POST['datestart'],
'dateend': request.POST['dateend'],
'usersegment': request.POST['usersegment'],
'segment_form': SegmentForm(request.POST),
'date_form': DateSelectForm(request.POST) })
else:
return render_to_response('activation_signupcount.html',
{'segment_form': SegmentForm(), 'date_form': DateSelectForm()})
template
{% extends "base_activation.html" %}
{% block content %}
<h2>Sign ups</h2>
<p>Number of users who have registered to the site between the dates entered</p>
{% endblock %}
{% block graph %}
{% if datestart %}
<p>This counts the number of <strong>{{ usersegment }}</strong> users who have successfully registered to the site (verified their email)
who joined between <strong>{{ datestart }}</strong> and <strong>{{ dateend }}</strong></p>
<img src="./activation_signupcount.png?usersegment={{ usersegment }}&datestart={{ datestart }}&dateend={{ dateend }}" />
{% endif %}
{% endblock %}
So I am returning the same page when a user submits the SegmentForm and DateSelectForms. To check if I should return the output (a graph), I am checking for the existence of datestart as seen in my template {% if datestart %} if it was submitted.
Is this a Djangoic way of doing it? I feel I ought to be checking for response == 'POST' rather than forcing the check variable to datestart.
Thanks
First, a few pointers to save you headaches when debugging the code. Instead of testing for request.method == ‘POST’, check whether the value you have attached to the submit button on your form(s) (in the template) is in the request.POST dictionary. I’m not sure whether you are submitting 2 forms with one “submit”-button, but if you do, why not write one form for it?
Also, always check whether your form is valid. This saves you a lot of headaches when rendering your graph, as the code for the graph can then safely make certain assumptions about the quality of the data it receives. Also, the user will know why the graph doesn’t render (he’ll get error messages in his form).
You could make the validation check in the template or in the view (the latter is recommended – program logic should reside in your views). If your forms are valid, they will get the “cleaned_data” properties, containing the validated data.
Off the top of my head, here’s what more Django-ic code would look like:
Then, in your template, first check if the forms are valid (the ‘display_graph’ variable is True if both forms are valid), and then access their cleaned_data properties to get the values you want. For instance: