Django - 模板中使用的自定义模型表单

时间:2015-09-03 06:02:07

标签: django django-forms django-templates

我一直在试图弄清楚如何创建自定义的html模板,该模板在提交时会上传到模型表单。我是Django的新手,所以到目前为止,我对表格上的Django文档感到有些困惑。我创建了一个自定义HTML模板:

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>

您可以注意到我已输入ID = logo。当我点击提交时,我希望将图像上传到我的ModelForm。

形式:

class UploadFileForm(ModelForm):

    logo = forms.ImageField(required=False)

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

型号:

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

我是否设计了我的HTML模板以将图像提交到模型表单?我试图避免使用{form.as_p},因为它没有做我想要的自定义。

1 个答案:

答案 0 :(得分:1)

您应该将form对象发送到模板并调用{{form.logo}}字段。

查看:

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))

模板:

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

定制

如果您想自定义输入字段,则应隐藏表单字段,如:

 <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>

现在要自定义输入,您应该显示自定义输入,并通过jQuery或JavaScript将自定义输入/按钮绑定到隐藏的表单徽标字段。

E.g:

如果要使用自定义按钮触发文件选择,则应执行以下操作:

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

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