Pulkit Sharma Pulkit Sharma - 1 month ago 11
Python Question

Django: Adding files to a form gives multiple argument error

Hi I have a Django project working perfectly fine. Now I need to add a field to it to upload documents.
However after adding the file stuffs, Django gives errors. Unable to solve it even after whole day Googling.

Models.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})


My Template

<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>


Error Logs:

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'

Answer

You override the __init__ method so that the first argument is user but you pass request.FILES instead. Change the line:

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

to

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

As a rule of thumb, try not to mix named and positional arguments, especially when you change the class constructor signature. Also consider changing your form name to SalesmanForm to be more compliant with PEP-8 class naming conventions.