1

I'd like to set custom name to a FileField object in my admin form so that it's html name attribute will not be equal to my instance field name.

class MyAdminForm(forms.ModelForm):
    file_field = forms.FileField()

    def __init__(self, *args, **kwargs):                                    
        if kwargs.has_key('instance'):
            instance = kwargs['instance']
            self.initial['image_file'] = instance.file_field

With this code I get <input type="file" name="file_field" /> and what I want to do is set it's name attribute to something else.

EDIT:

I accepted the answer below, but I have another question. Is it possible to construct variable number of FileField objects? I mean - what if I'd like to have 4 of those now, but under some circumstances only one? Will I have to declare all of those as a class fields, like file_field1, file_field2 and so on, or is it possible to add them to a dictionary, like that: { 'file_field1: FileField(), 'file_field2' : FileField() } - I actually tried it and got an error...

Marek M.
  • 3,799
  • 9
  • 43
  • 93
  • 1
    English is not your native language. **Avoid long sentences** like "I'd like to set custom name to a FileField object in my admin form so that it's html name attribute will not be equal to my instance field name.". Stick to subject+verb+complement. Your questions will suddently make more sense ! – jpic Mar 02 '12 at 13:20
  • Here are some tips from the above.. :) http://blog.stackoverflow.com/2010/10/asking-better-questions/ and like @jpic mentioned you'll get better answers.. – Lipis Mar 02 '12 at 13:39
  • Many thanks for language advices! :) – Marek M. Mar 02 '12 at 16:39

1 Answers1

2

The name attribute in the HTML is the same as the name in the form definition so if you don't want it to be file_field then don't call it file_field.

class MyAdminForm(forms.ModelForm):
    new_field = forms.FileField()
    # Rest of the form goes here
Mark Lavin
  • 24,664
  • 5
  • 76
  • 70
  • If there's no other way, then ok I'll do that, but does it mean that I can't declare a dictionary of FileFields? – Marek M. Mar 02 '12 at 16:32
  • Yes it's possible to dynamically create form fields. See http://stackoverflow.com/questions/5478432/making-a-django-form-class-with-a-dynamic-number-of-fields – Mark Lavin Mar 02 '12 at 16:52