Ryan113
Ryan113

Reputation: 686

Django - Custom Model Form used in a template

I've been trying to figure out how to create a custom html template that when submitted will upload to a model form. I'm newer to Django so so far i've been a little confused on the Django Docs on the forms. I have created a custom HTML Template it looks like:

HTML:

 <form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
   {% csrf_token %} 
       <img  id="image1" src="/media/{{ gallery.logo }}" alt="">
          <input type="file" name="logo" id="logo" multiple>
              <br>
          <input type="submit" value="Register" id="js-upload-submit" >
       </form>

You can notice that I have given the input ID = logo. When I click submit I would like this to upload an image to my ModelForm.

Form:

class UploadFileForm(ModelForm):

    logo = forms.ImageField(required=False)

    class Meta:
        model = Content
        fields = ['logo']

Models:

class Content(models.Model):
    logo = models.ImageField(upload_to=content_file_name, null=True, blank=True)

Is there anyway with the specific way I have designed my HTML template to submit the image to the Model Form? I am trying to avoid using { form.as_p } and such as it doesnt do the customization I would like.

Upvotes: 1

Views: 1717

Answers (1)

AlvaroAV
AlvaroAV

Reputation: 10553

You should send the form object to the template and call the {{form.logo}} field.

View:

if request.method == 'POST':  # When the form is submitted
    form = UploadFileForm(request.POST)
    if form.is_valid():
         new_content = form.save()
         # After the form.save a new model is created 
         # and the file is uploaded to the desired location
else: 
    form = UploadFileForm()

ctx = {}
ctx['form'] = form

return render_to_response('yourtemplate.html', ctx, context_instance=RequestContext(request))

Template:

 <form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
 {% csrf_token %} 
   {{form.logo}} 
 </form>

Customization:

If you would like to customize the input field, you should hide the form field like:

 <form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
   {% csrf_token %} 
   {{form.logo.as_hidden}} # This won't show the input
 </form>

And now to customize the input you should show your custom input and via jQuery or JavaScript bind the custom input/button to the hidden form logo field.

E.g:

If you want to trigger the file select with a custom button, you should do:

# ... Other code
<button class='btn btn-success yourclass' onClick='selectFile'>

<script>
  function selectFile(){
    $('#id_logo').click()
  }
<script>

Upvotes: 1

Related Questions