使用FileField进行Django表单验证

时间:2020-11-10 05:51:39

标签: django

使用基于类的通用视图CreateView来通过表单发布文件时遇到麻烦。以下是我到目前为止所拥有的。我不太确定如何处理文件,以及request.FILES是否正在发布文件,或者是否需要做其他事情来捕获表单中的文件信息。我已经尝试过遵循文档,但是运气不好。文件上传为空白字段。

views.py

# Create
class FileUploadCreateView(BSModalCreateView):
     template_name = 'fileupload/create-file.html'
     form_class = FileUploadModelForm
     success_message = 'Success: File was uploaded.'
     success_url = reverse_lazy('files_list')

     # Add required field my_user prior to posting form
     def form_valid(self, form):
         form = FileUploadModelForm(self.request.POST, self.request.FILES)
         self.object = form.save(commit=False)
         self.object.my_user = self.request.user
         self.object.file_status = 'ready'
         return super().form_valid(form)

forms.py

class FileUploadModelForm(BSModalModelForm):
class Meta:
    model = FileUpload
    fields = ['file_name', 'file_description', 'file_date_from', 'file_date_to','file_upload']

    widgets = {
        'file_name': forms.TextInput(attrs={'class':'form-control mb-3', 'id':'ruleset_name'}),
        'file_description': forms.Textarea(attrs={'rows':5}),
        'file_date_from': DatePickerInput(
            options={
                 "format": "MM/DD/YYYY",
                 "showClose": True,
                 "showClear": True,
                 "showTodayButton": True,
            }
        ),
        'file_date_to': DatePickerInput(
            options={
                 "format": "MM/DD/YYYY",
                 "showClose": True,
                 "showClear": True,
                 "showTodayButton": True,
            }
        ),
        'file_upload': forms.FileInput(attrs={'class':'form-control-file mb-3', 'id':'file_upload', 'type':'file', }),
    }

html

    {% load widget_tweaks %}


    <form method="post" action="" enctype="multipart/form-data">
      {% csrf_token %}
      
      <div class="modal-header">
        <h5 class="modal-title" style="color:#7a7a7a;">
          <i class="fas fa-plus-square fa-med pr-2 align-middle"></i>
          <span class="align-middle">ADD File</span>
        </h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

    <div class="modal-body">

    <div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
      {% for error in form.non_field_errors %}
        {{ error }}
      {% endfor %}
    </div>

    {% for field in form %}
      <div class="form-group">
        <label for="{{ field.id_for_label }}" style="font-size: small; color:#7a7a7a;">{{ field.label }}</label>
        {% render_field field class="form-control" %}
        <div class="{% if field.errors %} invalid{% endif %}">
          {% for error in field.errors %}
            <p class="help-block">{{ error }}</p>
          {% endfor %}
        </div>
      </div>
    {% endfor %}
  </div>

  <div class="modal-footer">
    <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
    <button type="button" class="submit-btn btn btn-primary pr-4 pl-4">Save</button>
  </div>
</form>

model.py

class FileUpload(models.Model):
    """
    Class for the creation of file uploads
    """
    id = models.AutoField(primary_key=True)
    my_user = models.ForeignKey('users.MyUser', on_delete=models.CASCADE, related_name='file_uploads', default=None)
    file_name = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Name')
    file_description = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Description')
    file_date_from = models.DateField(default=None, null=True, blank=False, verbose_name='File Date From')
    file_date_to = models.DateField(default=None, null=True, blank=False, verbose_name='File Date To')

    STATUS_CHOICES = (
        ('ready','Ready'),
        ('processed', 'Processed'),
        ('archived','Archived'),
    )
    file_status = models.CharField(max_length=9, choices=STATUS_CHOICES, default=None, blank=False, verbose_name='File Status')
    file_create_date = models.DateTimeField(verbose_name='File Create Date', auto_now_add=True)
    file_upload = models.FileField(upload_to='uploads/%Y/%m/%d/', default=None, verbose_name='File Upload', blank=True)

    class Meta:
        ordering = ['-file_create_date']
        constraints = [
            models.UniqueConstraint(fields=['my_user','file_name'], name='Unique MyUser File')
        ]

    def __str__(self):
        return self.file_name

2 个答案:

答案 0 :(得分:0)

很确定您忘记了将 enctype =“ multipart / form-data” 数据属性添加到模板中的 form 标记中。

可以肯定的是,您必须向我们提供模型,表单和模板代码。

答案 1 :(得分:0)

在视图上工作了一段时间后,我可以使用cleaned_data通过以下文件将其发布。

# Add required fields prior to posting form
def form_valid(self, form):
    self.instance = form.save(commit=False)
    self.instance.my_user = self.request.user
    self.instance.file_status = 'ready'
    self.instance.file_upload = form.cleaned_data['file_upload']
    return super().form_valid(form)