Django文件上传不显示

时间:2017-07-04 19:47:14

标签: django django-models django-forms django-templates django-views

我已经编写了文件上传代码,但它没有显示在我的目标页面上。 请帮我编辑代码或建议如何解决此问题。 其余字段显示但不显示文件字段

我的models.py

class Help(models.Model):
  researcher  = models.CharField(max_length=100)
  study = models.CharField(max_length=500)
  date = models.DateTimeField(auto_now_add=True)
  document = models.FileField(upload_to='documents/', null=True, blank=True)

forms.py

from django import forms
from .models import Help
from django.forms import ModelForm

class AboutHelp(forms.ModelForm):

    class Meta:
        model = Help
        fields = '__all__'

源页面

<form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form"> 
  {% csrf_token %}
      <label>Researcher Name(s):
        <input type="text" name="researcher"><br>
      <lable>Study Summary
        <textarea rows="10" cols="50" placeholder="Start typing..." maxlength="500" class="form-control" name="study"></textarea>
      <br>
      <label>Upload your IRB approval letter: 
        <input type ="file" id="irb-file" class="file_input" name="document"></label>
      <br>
      <input type = "submit" value="Submit" class="btn btn-primary" />
  </form>

views.py

def about_experiment(request, ex_link_name):
  researcher = None
  study = None
  posts = None
  exp = get_object_or_404(Experiment,link_name = ex_link_name)
  high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
  context = {
    'request': request,
    'exp':exp,
    'high_scores': high_scores,
    'awards':AwardItem.objects.filter(experiment=exp,visible=True),
  }

  if exp.about_file:
    context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()
    return render(request, 'about_experiment.html', context)

  if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)
        posts = Help.objects.filter().order_by('-date')[0]
        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            researcher = form.cleaned_data['researcher']
            study = form.cleaned_data['study']
            document = form.cleaned_data['document']

  else:
      form = AboutHelp()
      posts = Help.objects.filter().order_by('-date')[0]
      return render(request, 'about_experiment.html', {'posts': posts})  
  return render(request, 'about_experiment.html', {'posts': posts})

目标网页

  <h4><b>{{ posts.researcher }}</b></h4>
          <p>{{ posts.study }}</p>
          <p>Uploaded file is : {{ posts.document }}</p>

1 个答案:

答案 0 :(得分:1)

您检查过您的文件已保存吗?我认为你还没有理解Django表格的使用。这是how to。你正在创建表单,但你手动显示字段,在视图中,你可以通过forms.cleaned_data获取数据。另外,要保存文件,您需要定义<form enctype="multipart/form-data" >这里是why