django fileupload表单无法提交和上传

时间:2016-11-18 19:13:18

标签: python django django-views

我尝试使用django向导视图从表单上传文件,该表单是多种形式之一。但是,当我上传文件并点击提交时,该文件只会消失,我会得到一个'这个字段是必需的'错误。

Models.py

class Bill(models.Model):
    service = models.ForeignKey(UserService)
    bill = models.FileField(upload_to='bills', validators=[validate_file_extension])
    raw_data = models.TextField(null=True)
    meta_data = models.TextField(null=True)

Forms.py

class BillUploadForm(forms.ModelForm):
    class Meta:
        model = models.Bill
        fields = ['bill']

views.py

SIGNUP_FORMS = [
    ('signup', SignupForm),
    ('address', AddressForm),
    ('direct_debit', UserDirectDebitForm),
    ('account', AccountForm),
    ('user_service', UserServiceForm),
    ('bill_upload', BillUploadForm),
]

TEMPLATES = {
    'signup': 'site/signup.html',
    'address': 'site/signup_address.html',
    'direct_debit': 'site/signup_directdebit.html',
    'account': 'site/signup_directdebit.html',
    'user_service': 'site/signup_directdebit.html',
    'bill_upload': 'site/signup_directdebit.html',
}


class SignupWizard(SessionWizardView):
    location = os.path.join(settings.MEDIA_ROOT, 'temp', 'files')
    file_storage = FileSystemStorage(location)

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            return redirect(settings.LOGIN_REDIRECT_URL)
        return super().dispatch(request, *args, **kwargs)

    def done(self, form_list, form_dict, **kwargs):
        cd = form_dict['signup'].cleaned_data
        user = User.objects.create_user(
            username=cd['email'].split('@')[0],
            email=cd['email'],
            password=cd['password1'],
            first_name=cd['first_name'],
            last_name=cd['last_name'],
        )
        user.save()

        address = form_dict['address'].save(commit=False)
        address.user = user
        address.save()

        direct_debit = form_dict['direct_debit'].save(commit=False)
        direct_debit.user = user
        direct_debit.save()

        account = form_dict['account'].save(commit=False)
        account.address = address
        account.payment = direct_debit
        account.save()

        user_service = form_dict['user_service'].save(commit=False)
        user_service.account = account
        user_service.save()

        bill_upload = form_dict['bill_upload'].save(commit=False)
        bill = form_dict['bill_upload'].cleaned_data['bill']
        bill_upload.bill = bill
        bill_upload.service = user_service
        bill_upload.save()
        self.file_storage.delete(bill.name)

        complete_signup(self.request, user, settings.ACCOUNT_EMAIL_VERIFICATION, settings.LOGIN_REDIRECT_URL)
        return redirect(settings.LOGIN_REDIRECT_URL)

1 个答案:

答案 0 :(得分:1)

您尚未提供模板代码。查看您的代码,并确保在<form>中包含enctype="multipart/form-data"