使用Modelform上传Django文件

时间:2018-07-27 09:03:35

标签: django django-forms django-templates

我目前正在努力使用Django Modelform上传文件。

表单本身如下所示:

class AddAzienda(ModelForm):
    class Meta:
        model = Azienda
        fields = ('logo', 'nome', 'indirizzo', 'citta', 'provincia', 'cap', 'p_iva', 'rea', 'email', 'top_pdf', 'bottom_pdf', 'is_active')

这是负责模型创建的视图

if request.method == "POST":
        form = AddAzienda(request.POST, request.FILES)
        if form.is_valid():
            print("valid")
            instance = form.save(commit=False)
            action.send(request.user, verb="ha creato l'azienda", target=instance, ip=get_ip(request))
            messages.success(request, "Azienda <strong>" + instance.nome +  "</strong>  configurata con successo") 
            instance.save()
            return redirect("/aziende/")
    else:
        form = AddAzienda()
    context = {"form":form, "title": "Aggiungi Azienda", "parent":"Amministrazione","page_title": "Aziende configurate", "form_title": "Aggiungi Azienda","pul": "Salva", "link_back":"/aziende/"}
    return render(request, "azienda_add.html", context)

表单模板包含正确的enctype(根据docs),并且字段似乎已正确命名。

这是徽标字段的示例:

                            <label class="col-lg-2 col-form-label">Logo</label>
                            <div class="col-lg-4">
                                <div class="custom-file">
                                        <input type="file" class="custom-file-input" name="logo" id="id_logo" value="{{azienda.logo.url}}" required>
                                        <label class="custom-file-label" for="id_logo">Seleziona file</label>
                                </div>

你们能帮我吗?

谢谢

0 个答案:

没有答案