python-django file upload 'key error' - python

I am using python 3.2 & django 1.6. I want to upload to upload a 'csv' file and read data inorder to insert it into database(postgresql). Here is my code
Template
<form id = "ListForm" name = "ListForm" action = "" method = 'POST' enctype="multipart/form-data">
<table>
<tr>
<td>PM List</td>
<td><input type="file" name="file_pm" id="file_pm" ></td>
</tr>
<tr><td><input type="submit" value="Upload" name="pmUpload" id="pmUpload" class="button"></td></tr>
</table>
</form>
Python code is:
import cgi
def pmUpload(request):
form = cgi.FieldStorage()
fileitem = form["file_pm"]
I got 'KeyError' in the lastline of the above python code.I was trying to read data one by one.
And the full traceback error is
Environment:
Request Method: POST
Request URL: http://MYURL/cc/pmList/
Django Version: 1.6.5
Python Version: 3.2.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ccApp')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/env/ccENV/lib/python3.2/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/env/ccENV/lib/python3.2/site-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/home/env/ccENV/lib/python3.2/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/home/env/cccENV/ccc/ccApp/pmList.py" in pmUpload
19. fileitem = form["file_pm"]
File "/usr/lib/python3.2/cgi.py" in __getitem__
575. raise KeyError(key)
Exception Type: KeyError at /cc/pmList/
Exception Value: 'file_pm'
How to read data in python 3.2 from the uploaded file(data.csv)

The file should be in request.FILES['file_pm'].

Related

Django Form Validation Error Not Showing In Template

my issue is exactly as the problem states...I am unable to get form validation errors to work. I will post what I am currently trying below. Please let me know how I can amend my code in order to get this working. Currently, I can even successfully submit the form with any name. So clearly what I have set in forms.py is not even working...
forms.py
class PackingListForm(forms.ModelForm):
class Meta:
model = PackingList
fields = ['Exporter', 'Consignee', 'Reference_Number', ... ]
def clean_test_value(self):
data = self.cleaned_data.get('Exporter')
if not Exporter == 'Jeff':
raise forms.ValidationError('ahhhh Error!')
return data
template (packlist.html)
<td rowspan="3"colspan="2">Exporter: {{ form.Exporter }}
{% for error in form.Exporter.errors %}
<P class='help is-danger'>{{ error }}</p>
{% endfor %}
</td>
views.py
def PackingListView(request):
if request.method == "POST":
form = PackingListForm(request.POST)
if form.is_valid():
.....do stuff here......
else:
return render(request, 'packlist.html', {'form': form})
else:
form = PackingListForm()
return render(request, 'packlist.html', {'form': form})
traceback
Request Method: POST
Request URL: http://127.0.0.1:8000/create/packing_list
Django Version: 1.11
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Poseidon',
'crispy_forms',
'bootstrap_modal_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner
41. response = 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/andrews/Desktop/WBU2/Poseidon/views.py" in PackingListView
188. if form.is_valid():
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in is_valid
183. return self.is_bound and not self.errors
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in errors
175. self.full_clean()
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in full_clean
384. self._clean_fields()
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in _clean_fields
405. value = getattr(self, 'clean_%s' % name)()
File "/Users/andrews/Desktop/WBU2/Poseidon/forms.py" in clean_Exporter
52. if not Exporter == 'Greg':
Exception Type: NameError at /create/packing_list
Exception Value: global name 'Exporter' is not defined
Since the name of the field is Exporter, the cleaning function should be clean_Exporter:
class PackingListForm(forms.ModelForm):
class Meta:
model = PackingList
fields = ['Exporter', 'Consignee', 'Reference_Number']
def clean_Exporter(self):
data = self.cleaned_data.get('Exporter')
if data != 'Jeff':
raise forms.ValidationError('ahhhh Error!')
return data
Note: normally the name of the fields in a Django model are written in snake_case, not PerlCase, so it should be: exporter instead of Exporter.

django format_html not working with string_concat

I am trying to display a two line error message to a user. All attempts I have made have failed and I cannot figure this out, despite searching SO & google.
The error I am getting is:
Exception Type: IndexError
Exception Value: tuple index out of range
The issue seems to be the use of the format_html() with the string_concat().
Here is my python code:
from django.utils import translation
from django.utils.html import format_html
from django.utils.translation import string_concat
from django.utils.translation import ugettext_lazy as _
....
if not request.user.is_staff and language_versions_num_enabled > max_languages:
error_message = format_html(
string_concat(
_(u'You are only permitted <b>{}</b> <u>enabled</u> Language Versions for the selected <b>{}</b> subscription plan.'),
' <icon class="fa fa-frown-o icon_size26 icon_padding"></icon>',
'<br /><br />',
_(u'Either select a different subscription plan or disable <b>{}</b> of your <b>{}</b> <u>enabled</u> Language Versions.'.format(max_languages, stripe_plan['title'], language_versions_num_enabled-max_languages, language_versions_num_enabled))
)
)
messages.add_message(request, messages.ERROR, error_message)
else:
I am really hoping someone can point out what I am doing wrong here.
EDIT
I am using django 1.10 and python 3.5.2.
Here is the stack trace:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/subscription/subscription/
Django Version: 1.10.5
Python Version: 3.5.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.staticfiles',
'admin_honeypot',
'axes',
'rest_framework',
'rest_framework.authtoken',
'captcha',
'my_app.contact',
'djstripe',
'my_app.common',
'my_app.users',
'my_app.core',
'imagekit',
'parsley',
'registration',
'templatetag_handlebars',
'settings_context_processor',
'crispy_forms',
'lockdown',
'rosetta',
'raven.contrib.django.raven_compat')
Installed Middleware:
('raven.contrib.django.middleware.SentryMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'my_app.users.middleware.LocaleOverrideMiddleware',
'django.middleware.locale.LocaleMiddleware',
'my_app.users.middleware.AdminLocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'lockdown.middleware.LockdownMiddleware')
Traceback:
File "C:\Users\laptop\desktop\my_app\env3\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Users\laptop\desktop\my_app\env3\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response
249. response = self._get_response(request)
File "C:\Users\laptop\desktop\my_app\env3\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\laptop\desktop\my_app\env3\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\laptop\desktop\my_app\env3\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Users\laptop\desktop\my_app\env3\lib\site-packages\django\views\decorators\http.py" in inner
40. return func(request, *args, **kwargs)
File "C:\Users\laptop\desktop\my_app\my_app\core\decorators.py" in wrapper
21. return f(request, *args, **kwargs)
File "C:\Users\laptop\desktop\my_app\my_app\core\views\user_settings_views.py" in subscription
402. _(u'Either select a different subscription plan or disable <b>{}</b> of your <b>{}</b> <u>enabled</u> Language Versions.'.format(max_languages, stripe_plan['title'], language_versions_num_enabled-max_languages, language_versions_num_enabled))
File "C:\Users\laptop\desktop\my_app\env3\lib\site-packages\django\utils\html.py" in format_html
106. return mark_safe(format_string.format(*args_safe, **kwargs_safe))
File "C:\Users\laptop\desktop\my_app\env3\lib\site-packages\django\utils\functional.py" in __wrapper__
112. return getattr(res, method_name)(*args, **kw)
Exception Type: IndexError at /subscription/subscription/
Exception Value: tuple index out of range
You put format in the wrong place. Try this:
error_message = format_html(
string_concat(
_(u'You are only permitted <b>{}</b> <u>enabled</u> Language Versions for the selected <b>{}</b> subscription plan.'),
' <icon class="fa fa-frown-o icon_size26 icon_padding"></icon>',
'<br /><br />',
_(u'Either select a different subscription plan or disable <b>{}</b> of your <b>{}</b> <u>enabled</u> Language Versions.')
).format(max_languages, stripe_plan['title'], language_versions_num_enabled-max_languages, language_versions_num_enabled)
)

Django - Autocomplete_Light's "Add Another" popup declares: "'initial' is an invalid keyword argument for this function"

I am working on getting the "add another" popup to work with django-autocomplete_light.
Following along in the docs:
http://django-autocomplete-light.readthedocs.org/en/latest/addanother.html
I have set up my URLs:
import autocomplete_light.shortcuts as al
from AlmondKing.FinancialLogs import models
from AlmondKing.FinancialLogs import forms
urlpatterns = [
url(r'^branches/autocreate/$', al.CreateView.as_view(
model=models.CompanyBranch, form_class=forms.CompanyBranch),
name='branch_autocreate'),
]
and my autocomplete_light_registry.py
al.register(CompanyBranch,
search_fields=['^branch_name'],
attrs={
'placeholder': 'Branch',
'data-autocomplete-minimum-characters': 1,
},
widget_attrs={
'data-widget-maximum-values': 1,
'class': 'modern-style',
},
add_another_url_name='company:branch_autocreate',
)
However, when I click the plus sign to add a new related object, I get the following error:
TypeError at /company/branches/autocreate/
'initial' is an invalid keyword argument for this function
I've been trying to find a way to do this for a while and I'm so close!
Now, I am hoping someone can read the traceback and help me understand what went wrong:
Environment:
Request Method: GET
Request URL: http://localhost:8000/company/branches/autocreate/?_popup=1&winName=id_branch
Django Version: 1.8.2
Python Version: 3.4.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'AlmondKing.InventoryLogs',
'AlmondKing.FinancialLogs',
'AlmondKing.AKGenius',
'autocomplete_light')
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',
'AlmondKing.AKGenius.middleware.RequireLoginMiddleware')
Traceback:
File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\edit.py" in get
245. return super(BaseCreateView, self).get(request, *args, **kwargs)
File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\edit.py" in get
205. form = self.get_form()
File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\views\generic\edit.py" in get_form
74. return form_class(**self.get_form_kwargs())
File "C:\Users\Adam\Envs\AlmondKing\lib\site-packages\django\db\models\base.py" in __init__
480. raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
Exception Type: TypeError at /company/branches/autocreate/
Exception Value: 'initial' is an invalid keyword argument for this function
Try this:
add_another_url_name='company:branch_autocreate',
add_another_url_name='branch_autocreate',

django-avatar combined with django-notification gives an error

I have installed django-avatar and django-notification (django-avatar uses django-notification, if the latter is installed, in order to send necessary messages to user).
However when I upload/change/delete my avatar I get this error:
Request Method: POST
Request URL: http://localhost:8000/avatar/change/
Django Version: 1.3
Python Version: 2.6.4
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'grappelli',
'filebrowser',
'tinymce',
'south',
'avatar',
'django.contrib.admin',
'notification',
'tipleaders.main']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Tools\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Tools\Python26\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Tools\Python26\lib\site-packages\django_avatar-1.0.5-py2.6.egg\avatar\views.py" in change
77. notification.send([request.user], "avatar_updated", {"user": request.user, "avatar": avatar})
File "C:\Tools\Python26\lib\site-packages\django_notification-0.2-py2.6.egg\notification\models.py" in send
351. return send_now(*args, **kwargs)
File "C:\Tools\Python26\lib\site-packages\django_notification-0.2-py2.6.egg\notification\models.py" in send_now
276. reverse("notification_notices"),
File "C:\Tools\Python26\lib\site-packages\django\core\urlresolvers.py" in reverse
391. *args, **kwargs)))
File "C:\Tools\Python26\lib\site-packages\django\core\urlresolvers.py" in reverse
337. "arguments '%s' not found." % (lookup_view_s, args, kwargs))
Exception Type: NoReverseMatch at /avatar/change/
Exception Value: Reverse for 'notification_notices' with arguments '()' and keyword arguments '{}' not found.
django-avatar worked neatly just before django-notification was installed.
What went wrong?
URL notification_notices does not exist. Install django-notification urls, add to urls.py:
url('notification/', include('notification.urls')),
I recommend that you review your installation of django-notification.

Django attribute error: 'module' object has no attribute 'is_usable'

I got the following error when calling the url in Django.
It's working before, I guess it's related with some accidental changes I made, but I have no idea what they are.
Thanks before for the help,
Robert
Environment:
Request Method: GET Request URL: http://localhost:8000/time/ Django Version: 1.2 Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'djlearn.books'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware')
Traceback: File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args,
**callback_kwargs) File "/Users/rhenru/Workspace/django/djlearn/src/djlearn/../djlearn/views.py" in current_datetime
16. return render_to_response('current_datetime.html',{'current_date':now,}) File "/Library/Python/2.6/site-packages/django/shortcuts/__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args,
**kwargs), **httpresponse_kwargs) File "/Library/Python/2.6/site-packages/django/template/loader.py" in render_to_string
181. t = get_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in get_template
157. template, origin = find_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template
128. loader = find_template_loader(loader_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template_loader
111. if not func.is_usable:
Exception Type: AttributeError at /time/ Exception Value: 'module' object has no attribute 'is_usable'
It looks like Django is looking for a usable template loader, but is finding something in settings.TEMPLATE_LOADERS that isn't honoring the template loader function protocol (described briefly here.)
Is it possible that one of your recent changes was to either settings.TEMPLATE_LOADERS or to a custom template loader? If the latter, your template function needs an is_usable attribute, presumably set to True.

Categories