Django多文件上传失败

时间:2011-11-13 13:02:40

标签: python django django-models django-forms

我有一个HTML页面,里面有2个Django表单,所有这些都在同一个<form>..</form>标记中。一切都很好,除非我尝试上传多个文件。

每个表单都有自己的图像,由于某种原因,我只能保存第一个表单中的图像。来自第二种形式的其他数据仍然会被保存,但没有任何图像。我没有看到任何错误或异常,所以我不知道出了什么问题:s。

这是我的views.py

def display_form(request):
if request.method == 'POST':
    form_team = TeamForm(request.POST, request.FILES, prefix="team")
    form_player = PlayerForm(request.POST, request.FILES, prefix="play")
    #form_ketua = KetuaForm(request.POST, request.FILES, prefix="ketua")

    if all([form.is_valid() for form in [form_team, form_player]]):
        # save Team data first, overwrite if exists
        try:
            team = Team.objects.get(kota=form_Team.cleaned_data['name'])
            team.profil = form_Team.cleaned_data['profil']
            team.save()
        except Team.DoesNotExist:
            team = Team(**form_Team.cleaned_data)
            team.save()

        play = form_Player.save(commit=False)
        play.name = team
        play.save()

else:
    form_team = TeamForm(prefix="team")
    form_player = PlayerForm(prefix="play")
    #form_ketua = KetuaForm(prefix="ketua")
    print "a"

# list with tuple (form, legend) to pass as context
forms = [(form_Team, 'Team Data'),
         (form_Player, 'Player Profile'),
        ]

return render_to_response(
    'form/team.html', 
    {
        'formlist': forms,
    },
)

我做错了什么?

编辑:这是我的模板

{% extends "base.html" %}

{% block title %}Form - {{ title }}{% endblock %}

{% block content %}
<form action="." method="POST" enctype="multipart/form-data">{% csrf_token %}
{% for formitem in formlist %}
  {% if formitem.1 %}
  <fieldset>
      <legend>{{ formitem.1 }}</legend>
  {% endif %}
    {{ formitem.0.non_field_errors }}
    {% for field in formitem.0.visible_fields %}
      <div class="formfield">
      {{ field.errors }}
      {{ field.label_tag }} {{ field }}
  </div>
    {% endfor %}
  {% if formitem.1 %}
  </fieldset>
  {% endif %}
{% endfor %}
<div id="formbuttons">
  <input type="submit" value="Submit" class="button">
  <input type="reset" value="Reset" class="button">
</div>
</form>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

看起来您错过了play.save()(使用commit=False保存表单)