gpt4 book ai didi

python - Django:将文件添加到表单会出现多个参数错误

转载 作者:行者123 更新时间:2023-12-01 03:35:55 25 4
gpt4 key购买 nike

嗨,我有一个 Django 项目运行得很好。现在我需要向其添加一个字段来上传文档。但是添加文件内容后,Django 出现错误。即使经过一整天的谷歌搜索也无法解决它。

模型.py

class salesman(models.Model):
user=models.ForeignKey(settings.AUTH_USER_MODEL)
company=models.ForeignKey(Organisation,related_name='salesmancomp')
salesman_name=models.CharField(max_length=250)
salesman_address=models.CharField(max_length=750,null=True,blank=True)
salesman_PAN=models.CharField(max_length=250,null=True,blank=True)
salesman_commission_rate=models.FloatField(null=True,blank=True)
attachment = models.FileField(null=True,blank=True)

class Meta:
unique_together=(('company','salesman_name'),)

def __str__(self):
return self.salesman_name

forms.py

class salesmanform(forms.ModelForm): 
def __init__(self,user, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(salesmanform, self).__init__(*args, **kwargs)

class Meta:
model=salesman
fields=('salesman_name','salesman_PAN','salesman_commission_rate','salesman_address','attachment',)
widgets = {
'salesman_address': forms.Textarea
}
def clean(self):
cleaned_data=self.cleaned_data
salesman_name=cleaned_data['salesman_name']
pk=self.instance.pk
insert = pk ==None
if insert:
try:
salesman.objects.get(salesman_name=salesman_name,company=self.request.user.company.entity)
except salesman.DoesNotExist:
pass
else:
raise forms.ValidationError("Salesman already exist.")
else:
pass
return cleaned_data

Views.py

@login_required
def salesmancreate(request):

action="Salesman Creation"
if request.method == 'POST':
rec_form=salesmanform(request.FILES,request=request,user=request.user,data=request.POST)
if rec_form.is_valid():
new_rec = rec_form.save(commit=False)
new_rec.user = request.user
new_rec.company=request.user.company.entity
new_rec.save()
return HttpResponseRedirect(reverse('salesmancreate'),{'section':'added'},messages.add_message(request, messages.SUCCESS,'Salesman added Succesfully'))
else:
rec_form=salesmanform(request=request,user=request.user)
receivablescreated=salesman.objects.filter(company=request.user.company.entity).order_by('-id')
return render(request,'account/salesman.html',{'rec_form':rec_form,'receivablescreated':receivablescreated,'action':action})

我的模板

<form action="." method="post">

<div class="form-group">

{{ rec_form.salesman_name|attr:"class:form-control"|attr:"placeholder:Salesman Name"}}
</div>

<div class="input-group margin-b-20">

{{ rec_form.salesman_commission_rate|attr:"class:form-control"|attr:"placeholder:Commission Perentage" }}
<span class="input-group-addon"><i class="fa fa-envelope-o fa-percent"></i></span>
</div>
<div class="form-group">

{{ rec_form.salesman_PAN|attr:"class:form-control"|attr:"placeholder:PAN of Salesman" }}
</div>
<div class="form-group">

{{ rec_form.salesman_address|attr:"class:form-control"|attr:"style:height: 83px;"|attr:"placeholder:Address of Salesman" }}
</div>
<div class="form-group">

{{ rec_form.attachment|attr:"class:form-control"|attr:"style:height: 83px;"|attr:"placeholder:Address of Salesman" }}
</div>


<div class="form-group clearfix">
<div class="pull-right">
{% csrf_token %}
<button type="submit" class="btn btn-success rounded">Save</button>
</div>
</div>
</form>

错误日志:

TypeError at /salesmancreate/

__init__() got multiple values for keyword argument 'user'

Request Method: POST
Request URL: http://127.0.0.1:8000/salesmancreate/
Django Version: 1.10
Exception Type: TypeError
Exception Value:

__init__() got multiple values for keyword argument 'user'

Exception Location: /Users/pulkitsharma/Documents/workspace/tiktant/invoice/views.py in salesmancreate, line 422
Python Executable: /usr/bin/python
Python Version: 2.7.10
Python Path:

['/Users/pulkitsharma/Documents/workspace/tiktant',
'/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
'/Library/Python/2.7/site-packages']

Server time: Thu, 3 Nov 2016 06:45:34 +0000

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/salesmancreate/

Django Version: 1.10
Python Version: 2.7.10
Installed Applications:
('invoice',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'widget_tweaks')
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',
'django.middleware.security.SecurityMiddleware')



Traceback:

File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)

File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)

File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)

File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)

File "/Users/pulkitsharma/Documents/workspace/tiktant/invoice/views.py" in salesmancreate
422. rec_form=salesmanform(request.FILES,request=request,user=request.user,data=request.POST)

Exception Type: TypeError at /salesmancreate/
Exception Value: __init__() got multiple values for keyword argument 'user'

最佳答案

您重写了__init__方法,以便第一个参数是user,但您传递了request.FILES。更改行:

rec_form=salesmanform(request.FILES,request=request,user=request.user,data=request.POST)

rec_form = salesmanform(user=request.user, data=request.POST,
files=request.FILES, request=request)

根据经验,尽量不要混合命名参数和位置参数,尤其是当您更改类构造函数签名时。另请考虑将表单名称更改为 SalesmanForm 以更符合 PEP-8类命名约定。

关于python - Django:将文件添加到表单会出现多个参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40395455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com