Django从表单访问request.user数据以及文件提交

时间:2017-09-10 05:05:20

标签: django-forms django-views

我正在尝试根据request.user数据显示包含许可证类型数据的表单。 使用用户作为视图中表单的输入变量时,表单工作正常。 但是,当我尝试使用相同的表单上传文件并使用request.File。

我收到以下错误。

forms.py

from django import forms

class BusinessRequestForm(forms.Form):
    business_name = forms.CharField(label='Enter Business Name', widget=forms.Textarea, help_text="Enter the Name of the business you require" )
    business_type= forms.ChoiceField(label='Select Your Business Type', choices=BUSINESS_TYPE, help_text="If your business type is not present. Enter details in Additional info" )
    license_type =forms.ModelChoiceField(label='Select the license type',queryset=Pricing.objects.none(),help_text="Check Pricing on Main Page Pricing")
    additional_detail=forms.CharField(label='Enter any additional details', widget=forms.Textarea, help_text="Give details about your Tax Structure", required=False)
    tax_structure=forms.CharField(label='Tax Structure ', widget=forms.Textarea, help_text="Describe Your Tax Structure If Applicable",required=False)
    sales_invoice=forms.FileField(help_text="Upload your present Sales Invoice if any",required=False)
    purchase_invoice=forms.FileField(help_text="Upload your present Purchase Invoice if any",required=False)
    pay_slip=forms.FileField(help_text="Upload your present Pay Slip if any",required=False)
    talley_file=forms.FileField(help_text="Upload your present Talley Export if any",required=False)

def __init__(self,input_user,*args,**kwargs):
    super(BusinessRequestForm,self).__init__(*args,**kwargs)
    select_user=MyProfile.objects.get(user=input_user)
    price=Pricing.objects.all().filter(pricing_region=select_user.region).filter(target=select_user.sales_partner)
    self.fields['license_type'].queryset=price

models.py

class Business_request(models.Model):
    user=models.ForeignKey("auth.User")
    business_name=models.CharField("Name of Business Required",max_length=200,help_text="Enter the name of the business")
    business_type=models.CharField("Select Business Type",max_length=200,choices=BUSINESS_TYPE,help_text="If your business type is not present,enter in additional details and select the closest type here")
    license_type=models.ForeignKey(Pricing)
    tax_structure=models.CharField("Tax Structure",max_length=200,help_text="Describe your Tax Structure",blank=True)
    additional_details=models.CharField("Enter any additional details",max_length=200,blank=True)
    sales_invoice=models.FileField(upload_to='businessReqForm',null=True,blank=True)
    purchase_invoice=models.FileField(upload_to='budinessReqForm',null=True,blank=True)
    pay_slip=models.FileField(upload_to='budinessReqForm',null=True,blank=True)
    talley_file=models.FileField(upload_to='budinessReqForm',null=True,blank=True)

views.py

@login_required
def businessRequestFormView(request):
    if request.method == 'POST':
        form = BusinessRequestForm(request.FILES,data=request.POST,input_user=request.user,)
        if form.is_valid():
            business_name=form.cleaned_data['business_name']
            business_type=form.cleaned_data['business_type']
            license_type=form.cleaned_data['license_type']
            additional_details=form.cleaned_data['additional_detail']
            tax_structure=form.cleaned_data['tax_structure']
            s=Business_request()
            s.user=request.user
            s.business_name=business_name
            s.business_type=business_type
            s.license_type=license_type
            s.additional_details=additional_details
            if request.FILES['sales_invoice']:
                sales_invoice=request.FILES['sales_invoice']
                s.sales_invoice=sales_invoice
            if request.FILES['purchase_invoice']:
                purchase_invoice=request.FILES['purchase_invoice']
                s.purchase_invoice=purchase_invoice
            if request.FILES['pay_slip']:
                pay_slip=request.FILES['pay_slip']
                s.pay_slip=pay_slip
            if request.FILES['talley_file']:
                talley_file=request.FILES['talley_file']
                s.talley_file=talley_file
            s.save()
            user=request.user
            sender='info@accountingbuddy.org'
            subject="AccountingBuddy.Org Business Setup Request Fm %s" % user.first_name
            message="Business Name : %s , Business Type: %s , License Type: %s, Additional Details : %s , User %s , Phone %s, Email %s" % (business_name,business_type,license_type, additional_details, request.user,user.myprofile.phone_no,user.email)
            recipients = ['keeganpatrao@gmail.com',]
            recipients +=[user.email,]
            send_mail(subject, message, sender, recipients)
            return HttpResponseRedirect(reverse('accountingbuddy:thanks'))
    else:
        form = BusinessRequestForm(input_user=request.user)
    return render(request, 'business_request_form.html', {'form': form})

错误

环境:

Request Method: POST
Request URL: https://website.com/accountingbuddy/businessrequest/submit/

Django Version: 1.10.7
Python Version: 3.5.2
Installed Applications:
('mezzanine.boot',
 'accountingbuddy',
 'nova',
 'bootstrap3',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.redirects',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.sitemaps',
 'mezzanine.conf',
 'mezzanine.core',
 'mezzanine.generic',
 'mezzanine.pages',
 'mezzanine.blog',
 'mezzanine.forms',
 'mezzanine.galleries',
 'mezzanine.twitter',
 'mezzanine.accounts',
 'filebrowser_safe',
 'grappelli_safe',
 'django.contrib.admin',
 'django.contrib.staticfiles',
 'django_comments')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'mezzanine.core.request.CurrentRequestMiddleware',
 'mezzanine.core.middleware.RedirectFallbackMiddleware',
 'mezzanine.core.middleware.TemplateForDeviceMiddleware',
 'mezzanine.core.middleware.TemplateForHostMiddleware',
 'mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware',
 'mezzanine.core.middleware.SitePermissionMiddleware',
 'mezzanine.pages.middleware.PageMiddleware')



Traceback:

File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/webapps/accounting/accounting_home/accounting_home/accountingbuddy/views.py" in businessRequestFormView
  49.       form = BusinessRequestForm(request.FILES,data=request.POST,input_user=request.user,)

Exception Type: TypeError at /accountingbuddy/businessrequest/submit/
Exception Value: __init__() got multiple values for argument 'input_user'

0 个答案:

没有答案