【问题标题】:Django Form test File upload , error show empty fieldDjango表单测试文件上传,错误显示空字段
【发布时间】:2019-01-02 04:14:30
【问题描述】:

我的测试表单有问题,即使我尝试了很多方法它也不接受文件上传,它只是返回文件上传字段不能为空的错误:

AssertionError: False is not true : <ul class="errorlist"><li>file<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

Test.py:

def test_applicant_form(self):
        placements = Position.objects.filter(published=True)[0]
        client = Client()
        file =  File(open('root/static/applications/file.pdf', 'rb'))
        data_set = {'name': 'Caleb', 'surname': 'Dvorszky',
            'phone_number': '+1963124575', 'city': 'Kansas City', 'country': 'United States', 'message': 'Would like to be there', 'file':file}
        form = ApplicantForm(data=data_set)
        self.assertTrue(form.is_valid(), form.errors)

甚至尝试过:

response = client.post(placements.get_absolute_url,data=data_set, content_type='multipart/form-data')

还是不行。

这是forms.py

class ApplicantForm(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'}))
    surname = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'}))
    phone_number = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'}))
    city = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'}))
    country = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'}))
    message = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control form-control-lg'}))
    file = forms.FileField(widget=forms.FileInput())

    class Meta:
        model = Candidate
        exclude = ['position', 'seen']

模型.py 这是表格填充数据时需要保存的模型

class Applicant(models.Model):
    date = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100)
    surname = models.CharField(max_length=100)
    phone_number = models.CharField(max_length=100)
    city = models.CharField(max_length=100)
    country = models.CharField(max_length=100)
    position = models.ForeignKey(
        Position, on_delete=models.CASCADE,
        related_name='applicants')
    cover_letter = models.TextField()
    file = models.FileField(upload_to='files/applications')
    seen = models.BooleanField(default=False, editable=False)

    ADMIN_DISPLAY = ['get_name', 'position', 'city', 'country', 'get_file', 'date']

    def get_name(self):
        return "%s %s" % (self.name, self.surname)
    get_name.short_description = 'Name'

    def get_file(self):
        return '<a href="%s%s" target="_blank">Download</a>' % (
            settings.BASE_DOMAIN_URL, self.file.url)
    get_file.allow_tags = True
    get_file.short_description = 'Download file'

这里是 views.py ,只是组成部分:

if request.method == 'POST':
        form = ApplicantForm(request.POST, request.FILES)
        if form.is_valid():
            applicant = form.save(commit=False)
            applicant.position = placement
            applicant.save()
            notification(applicant)
            messages.info(request, 'We received your application. See you soon!')
            return redirect('postions:position-post', placement.slug)
    form = ApplicantForm()

【问题讨论】:

    标签: python django


    【解决方案1】:

    您似乎没有正确传递文件。此外,您似乎正在尝试访问您未在表单中定义的 data 关键字参数。试试这个:记得从 django.core.files.uploadedfile 导入 `SimpleUploadedFile

      from django.core.files.uploadedfile import SimpleUploadedFile
    
      def test_applicant_form(self):
        placements = Position.objects.filter(published=True)[0]
        with open('root/static/applications/file.pdf', 'rb') as file:
          document = SimpleUploadedFile(file.name, file.read(), content_type='application/pdf')
        data_set = {'name': 'Caleb',
        'surname':'Dvorszky',
        'phone_number': '+1963124575',
        'city': 'Kansas City',
        'country':'United States',
        'message': 'Would like to be there',
        }
        form = ApplicantForm(data_set, {'file': document})
        self.assertTrue(form.is_valid(), form.errors)
    

    查看此link on testing 以进一步阅读。你也可以看看this link on testing file upload with django

    【讨论】:

    • 我又遇到了同样的错误AssertionError: False is not true : &lt;ul class="errorlist"&gt;&lt;li&gt;file&lt;ul class="errorlist"&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;
    • @havoc 我已经编辑了上传测试图像文件的答案。它适用于我的本地机器。将 content_type 关键字参数更改为 'application/pdf'
    猜你喜欢
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2021-01-01
    • 1970-01-01
    • 2018-01-06
    • 2021-07-28
    • 2015-07-10
    相关资源
    最近更新 更多