当Django中存在时,我应该如何允许FileField不需要上传新文件?

时间:2017-02-06 08:14:02

标签: django django-models django-forms

我有一个这样的模型:

class Assignment(models.Model):
    content = models.FileField(upload_to='xxx')
    other_val = models.CharField(...)  # not important

包装此模型的表单(ModelForm):

class AssignmentForm(ModelForm):
    class Meta:
        model = Assignment
        fields = ['content', 'other_val']

我的观点看起来像这样(为了简单起见,我跳过了request.POST/request.FILES。部分):

@login_required(login_url='/login/')
def create_assignment(request):
    form = AssignmentForm()
    # render form

@login_required(login_url='/login/')
def update_assignment(request, assignment_id):
    assignment = Assignment.objects.get(id=assignment_id)
    form = AssignmentForm(instance=assignment)

创建作业很好 - 它迫使我上传文件,这就是我想要的。但是当我想更新作业的内容(文件)时,它首先会显示以前上传的文件的链接(非常好!),然后是上传按钮,如下所示:

Currently: AssignmentTask_grading_script/grading_script_firing.py 
Change: [Choose File] no file chosen

但是我假设如果我不想替换这个文件,我只需点击提交按钮即可。不幸的是,当我点击提交按钮时,表单会抱怨我应该上传文件。如果文件已存在于数据库中,是否有办法使投诉无声?

1 个答案:

答案 0 :(得分:1)

按照之前的评论,也许是这样;

<强> 1。 forms.py

class AssignmentForm(forms.ModelForm):
    # as following @Rohan, to make it optional.
    content = forms.FileField(required=False)

    class Meta:
        model = Assignment
        fields = ['content', 'other_val']

<强> 2。 yourtemplate.html

<form method="post" enctype="multipart/form-data" action=".">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Save</button>
</form>

<script> 
{% if not form.content.value %}
  $('#id_content').attr({'required': 'required'});
{% endif %}
</script>
  

content的字段只有在以前没有价值的情况下才需要...