【问题标题】:Django - Can not upload file using my formDjango - 无法使用我的表单上传文件
【发布时间】:2019-07-30 07:34:20
【问题描述】:

情况如下:我对 Django 很陌生,我正在尝试使用我创建的表单上传一些文件。当我点击提交按钮时,在我的数据库中创建了一个新行,但是我使用 FileField 选择的文件没有上传。但是我可以通过管理页面上传文件而没有任何问题。

我一直在尝试寻找解决方案一段时间,但我仍然没有找到任何可以帮助我的东西,所以如果你们中的任何一个知道如何解决我的问题,我将非常感激。

在这里你可以找到一些与我的表单相关的代码:

forms.py

class PhytoFileForm(forms.ModelForm):
    class Meta:
        model = models.PhytoFile
        fields = ['general_treatment', 'other']

    def __init__(self, *args, **kwargs):
        super(PhytoFileForm, self).__init__(*args, **kwargs)

models.py

class PhytoFile(models.Model):
    date = models.DateTimeField("Date", default = datetime.datetime.now)
    general_treatment = models.FileField("Traitements généraux", upload_to='fichiers_phyto/', blank=True, null=True)
    other = models.FileField("Autres traitements", upload_to='fichiers_phyto/', blank=True, null=True)

    class Meta:
        verbose_name = "Liste - Fichier phyto"
        verbose_name_plural = "Liste - Fichiers phyto"

    def __str__(self):
        return str(self.date)

views.py

class AdminFichiersPhyto(View):
    template_name = 'phyto/phyto_admin_fichiers.html'
    form = forms.PhytoFileForm()

    def get(self, request):
        return render(request, self.template_name, {'form': self.form})

    def post(self, request):
        form = forms.PhytoFileForm(request.POST, request.FILES)
        form.save()
        return render(request, self.template_name, {'form': self.form})

phyto_admin_fichiers.html

{% block forms %}

{% if user.is_staff%}

    {% if messages %}
      <ul class="messages">
        {% for message in messages %}
           <div id='overlay-message' class="alert alert-danger alert-dismissible" role="alert">
           <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Fermer</span></button>
             {{ message }}
           </div>  
        {% endfor %}
      </ul>
    {% endif %}
    <p>
     <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Fertiweb" name="synchronisation"/>
    </p>

    <form method="post" action="" enctype="multipart/form-data">
      {% csrf_token %}
        <fieldset>
            <div style="display: inline-block; margin-left: 22%; text-align: center"><b>Traitements généraux</b>{{ form.general_treatment }}</div>
            <div style="display: inline-block; text-align: center"><b>Autres traitements</b>{{ form.other }}</div>
        </fieldset>

      <p style="margin-top: 2%">
        <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Traitements généraux" name="trtm_gen"/>
        <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Autre" name="autre"/>
      </p>

    </form>
{% endif %}
{% endblock %}

EDIT 1 在 Sangram 的回答之后 forms.py

class PhytoFileForm(forms.ModelForm):
    general_treatment = forms.FileField(widget=forms.FileInput)
    class Meta:
        model = models.PhytoFile
        fields = ['general_treatment', 'other']

    def __init__(self, *args, **kwargs):
        super(PhytoFileForm, self).__init__(*args, **kwargs)

编辑 2 我一直在尝试验证表单一段时间但没有成功..有人知道为什么吗?

forms.py

class PhytoFileForm(forms.ModelForm):
    general_treatment = forms.FileField(widget=forms.FileInput)
    class Meta:
        model = models.PhytoFile
        fields = ['general_treatment', 'other']

    def __init__(self, *args, **kwargs):
        super(PhytoFileForm, self).__init__(*args, **kwargs)

    def is_valid(self):
        valid = not bool(self.data.get('general_treatment', False)) and not bool(self.data.get('other', False))
        print("~~~~~~~~~> %s" % (format(not valid)))
        return not valid

我不知道为什么,但我的 not valid 等于 True 并且我返回它但我仍然收到一个错误,说它尚未经过验证......也许我做错了不应覆盖is_valid 方法

【问题讨论】:

  • 添加大写帖子&lt;form method="POST"
  • 刚试了没用:/
  • 在表单 .py 中添加 general_treatment = forms.FileField(widget=forms.FileInput) 并在开发者工具 > 预览或响应头中检查文件路径
  • 我已经尝试添加你告诉我的行(我不知道我是否把它放在你想要的地方^_^'你可以看到我把它放在 EDIT 我在帖子中所做的部分)我在响应标头中没有找到任何内容,但我在Headers 选项卡中看到了Form Data 中的文件名

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


【解决方案1】:

试试这个

forms.py

class PhytoFileForm(forms.ModelForm):
    class Meta:
        model = PhytoFile
        fields = ['general_treatment', 'other']

Views.py

class MeasurementProfileCreateView(CreateView):
    model = PhytoFile
    form_class = PhytoFileForm

    def get_success_url(self):
        return reverse_lazy('home')#Your success url 


    def post(self, request, *args, **kwargs):
        fileform = self.PhytoFileForm(self.request.POST, request.FILES)
        if fileform.is_valid():
            fileform.save()
        return HttpResponseRedirect(self.get_success_url())

查看上面的代码并根据您的代码进行更改

【讨论】:

  • 哦!我现在有新东西了!我有一个ValueError 告诉我,由于数据未验证,因此无法创建 PhytoFile!会尝试解决这个问题;)感谢您的解决方案! :D
  • 谢谢!如果一切顺利,我会告诉你^^'
  • 我真的找不到验证这个表格的方法......我开始紧张了 x)(我用我所做的修改编辑了我的帖子)
  • 检查你的数据库
  • 将其放入您的模板 {{ form }} 并检查您的获取请求响应
猜你喜欢
  • 1970-01-01
  • 2018-01-25
  • 2011-03-11
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 2017-11-08
  • 2021-12-31
  • 2020-01-08
相关资源
最近更新 更多