I am not sure if I should post this question here or in serverfault since it involves both django and nginx configuration files.
I have a django view that receives POST data from a form that contains file fields.
The request goes through an nginx module (upload module) that takes file upload fields, stores them to a disk location and then appends extra fields with the local path where each file can be found, along with their names and other metadata, and then strips the original file fields from the POST.
The fields that are appended are unfortunately not very flexible and their names contain either a period (.) or a dash (-).
This is all well and fine but the problem comes on the python side. If would like to validate the incoming POST data using a form, but the I don't know how to define a 开发者_开发知识库form that has fields with names containing periods or dashes. Is there a way to tell the django form that the field has a different name that the variable used to store it?
My workaround is to simply not use django forms and sanitize the incoming data in another way (how?).
Or if somebody has experience using the upload module in nginx and knows how to use the directives
upload_set_form_field $upload_field_name.name "$upload_file_name";
upload_set_form_field $upload_field_name.content_type "$upload_content_type";
upload_set_form_field $upload_field_name.path "$upload_tmp_path";
so that the $upload_field_name.XXXX appended fields don't use a period? (a dash works, but that again breaks python's identifiers, any other character breaks the configuration file)
Any recomendations in either case?
Thanks!
Ok, I think I found a way to answer my own question and I hope it helps someone.
The form I would use to handle the submitted POST with a field called "uploadedFile.name" would look something like this:
from django.forms import Form, fields
def UploadForm(Form):
someField = fields.CharField()
uploadedFile.name = fields.CharField()
Which of course does not work since we can't use a period in the identifier (uploadedFile.name).
The answer is to define the form fields using the fields dictionary of the Form class, where we can name the fields with a nice and arbitrary string:
def UploadForm(Form):
someField = fields.CharField()
def __init__(self, *args, **kwargs):
#call our superclasse's initializer
super(UploadForm,self).__init__(*args,**kwargs)
#define other fields dinamically:
self.fields["uploadedFile.name"]=fields.CharField()
Now we can use that form in a view and access uploadedFile.name's data through cleaned_data as we would any other field:
if request.method == "POST":
theForm = UploadForm(request.POST)
if theForm.is_valid():
theUploadedFileName=theForm.cleaned_data["uploadedFile.name"]
It works!
精彩评论