Simplifying Django Form Data
I am working on an api of sorts. This requires that I create several methods in which data is appended in a url as a string of GET-data. To access GET-data in a Django view, you simply use
request.GET['parameter']. However, it is a pain to write
request.GET['parameter'] about 20 times when the only thing that is changing is the name of the parameter.
To get around this, I have devised a simple solution:
def view_name(request):
params = ('param1', 'param2', 'param3', 'param4')
data = {}
for param in params:
param_value = request.GET[param]
data[param] = param_value
return HttpResponse("here is the dictionary of all of your GET-data: %s" % data)
Now you can easily alter GET (or POST) parameters without deleting and rewriting
request.GET['parameter'] for the nth time. The data is accessible in a dictionary. Just want the value for
param1? Just use
some_var = data[param1].
And
here is the code on my
favorite pastebin.
UPDATE: Upon using this, I realized there is a much simpler way to accomplish the same thing:
data = request.GET. Getting the value for
param1 is as easy as
data['param1']. I'll still leave this post up for learning experience purposes.
Alan
26 January 2009