[Django]-How to use non valid identifiers as django form field names

7đź‘Ť

âś…

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!

Leave a comment