'str' object has no attribute 'get' (Django) - django

Ahoy Mateys!
got a simple model with a simpel form here:
class Hardware(models.Model):
type_name = models.CharField(max_length=60)
def __unicode__(self):
return self.type_name
class HardwareForm(ModelForm):
class Meta:
model = Hardware
fields = ['type_name']
and this is used by my simple views function:
def createHardware(request):
if request.method == 'POST':
form = HardwareForm('request.POST')
if form.is_valid():
new_hardware = form.save()
return render_to_response('administration/overview.html')
else:
form = HardwareForm()
return render_to_response('administration/create_hardware.html', {
'form': form, }, context_instance = RequestContext(request))
this is the Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/ticket/createHardware/
Django Version: 1.6.6
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ticket')
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 "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\bachi_000\workspace\Help\src\ticket\views.py" in createHardware
155. if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
129. return self.is_bound and not bool(self.errors)
File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
121. self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
273. self._clean_fields()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
282. value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Python27\lib\site-packages\django\forms\widgets.py" in value_from_datadict
207. return data.get(name, None)
Exception Type: AttributeError at /ticket/createHardware/
Exception Value: 'str' object has no attribute 'get'
so i got several forms with much more data in it, and there is no problem to pass an empty form to the html page, fill it out and POST them back to the function to get the data in the form. run is_valid() and pass the data to a new instance of the model (to add some more data to it)
why do i get here this error?

You need to be passing in a dictionary to your HardwareForm, not a string.
Change in your views.py
form = HardwareForm('request.POST')
to:
form = HardwareForm(request.POST)

Related

django - TypeError at /admin/login/ has_module_perms() takes 2 positional arguments but 3 were given

I get an error when I login http://127.0.0.1:8000/admin.
I don't know where the error occurred.
This is the error message:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/
Django Version: 2.0.5
Python Version: 3.6.2
Installed Applications:
['users',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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 "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in login
382. self.each_context(request),
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in each_context
302. 'available_apps': self.get_app_list(request),
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in get_app_list
470. app_dict = self._build_app_dict(request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/sites.py" in _build_app_dict
418. has_module_perms = model_admin.has_module_permission(request)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/admin/options.py" in has_module_permission
506. return request.user.has_module_perms(self.opts.app_label)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/auth/models.py" in has_module_perms
422. return _user_has_module_perms(self, module)
File "/home/c/Softwares/anaconda3/envs/medic/lib/python3.6/site-packages/django/contrib/auth/models.py" in _user_has_module_perms
196. if backend.has_module_perms(user, app_label):
Exception Type: TypeError at /admin/login/
Exception Value: has_module_perms() takes 2 positional arguments but 3 were given
users/views.py:
from django.shortcuts import render, redirect
from .forms import RegisterForm
# Create your views here.
def index(request):
return render(request, 'index.html')
def register(request):
redirect_to = request.POST.get('next', request.GET.get('next', ''))
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
if redirect_to:
return redirect(redirect_to)
else:
return redirect('/')
else:
form = RegisterForm()
return render(request, 'users/register.html', context={'form': form, 'next': redirect_to})
this is a user login registration authentication code, and only have user app.
in the traceback seem the error didn't occured in my code, so i don't know where it is wrong.
user/models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
email = models.EmailField(verbose_name='email',
unique=True, error_messages={'unique': 'Email is already occupied'})
class Meta(AbstractUser.Meta):
pass
If use an AbstractBaseUser add arguments, or try overwriting the function, can use this:
def has_module_perms(self, *args): # or add
# ....
return True

Django: 'NoneType' object has no attribute 'user'

I am using Django User model for one of the select field.
However i am not able to pass only users linked to a commmon organisation/company.
I have a onetoone profile linking for each user. This one to onetoone model is again linked to organisation model.
Now need a form where select field should have users linked to organisation model.
Here is my form.py:
class taskaddform(forms.ModelForm):
def __init__(self,user, *args, **kwargs):
self.user = kwargs.pop('user', None)
self.request = kwargs.pop('request', None)
super(taskaddform, self).__init__(*args, **kwargs)
self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
class Meta:
model=tasktable
fields=('task','assigned_to','discription','documents',)
views.py:
#login_required
def taskadd(request):
if request.method=='POST':
form=taskaddform(request.POST,request.FILES,request.user)
if form.is_valid():
new_form=form.save(commit=False)
new_form.created_by=request.user
new_form.company=request.user.company.entity
new_form.save()
return HttpResponseRedirect(reverse('taskadd'),messages.add_message(request, messages.SUCCESS,'Task added succesfully.'))
else:
form=taskaddform(request.user)
return render(request,'taskadd.html',{'form':form})
Error Log:
Request Method: GET
Request URL: http://127.0.0.1:8000/task/taskadd/
Django Version: 1.10
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'user'
traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/task/taskadd/
Django Version: 1.10
Python Version: 2.7.10
Installed Applications:
('invoice',
'support',
'task',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'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/workspace1/tiktant/task/views.py" in taskadd
38. form=taskaddform(request.user)
File "/Users/pulkitsharma/Documents/workspace1/tiktant/task/forms.py" in __init__
11. self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
Exception Type: AttributeError at /task/taskadd/
Exception Value: 'NoneType' object has no attribute 'user'
Updated views.py.
#login_required
def taskadd(request):
if request.method=='POST':
form=taskaddform(request, request.POST,request.FILES,request.user)
if form.is_valid():
new_form=form.save(commit=False)
new_form.created_by=request.user
new_form.company=request.user.company.entity
new_form.save()
return HttpResponseRedirect(reverse('taskadd'),messages.add_message(request, messages.SUCCESS,'Task added succesfully.'))
else:
form=taskaddform(request)
return render(request,'taskadd.html',{'form':form})
and in your forms.py --
class taskaddform(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
self.request = request
super(taskaddform, self).__init__(request, *args, **kwargs)
self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)

Exception Value: 'Form' object has no attribute 'attribute'

I'm trying to override clean() method of the form to check, whether attribute IBAN is unique or not. Each user can have IBAN. For some reason, django says that form has no attribute IBAN which isn't true. As you can see it's a first attribute of the form.
Do you know what's problem?
class TranslatorRegistrationForm(forms.Form):
IBAN = forms.CharField(max_length=40, required=True)
first_name = forms.CharField(max_length=40, required=True)
last_name = forms.CharField(max_length=40, required=True)
languages = forms.ModelMultipleChoiceField(Language.objects.all(), label='Languages: ',
help_text="You can choose from UNKNOWN levels, to gain level, you will be tested")
def __init__(self,user,*args, **kwargs):
super(TranslatorRegistrationForm, self).__init__(*args, **kwargs)
self.user = user
def clean(self):
cleaned_data = super(TranslatorRegistrationForm, self).clean()
if len(UserProfile.objects.filter(IBAN=self.IBAN).exclude(user=self.user))>0:
raise ValidationError
return cleaned_data
TRACEBACK:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/register-as-translator/
Django Version: 1.8.12
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',
'SolutionsForLanguagesApp',
'crispy_forms',
'super_inlines',
'django_tables2',
'language_tests',
'smart_selects',
'django_extensions',
'constance',
'constance.backends.database',
'nested_inline')
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',
'django.middleware.locale.LocaleMiddleware')
Traceback:
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\SolutionsForLanguagesApp\views.py" in register_as_translator
110. if register_as_translator_form.is_valid():
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in is_valid
184. return self.is_bound and not self.errors
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in errors
176. self.full_clean()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in full_clean
393. self._clean_form()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in _clean_form
417. cleaned_data = self.clean()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\SolutionsForLanguagesApp\forms.py" in clean
116. if len(UserProfile.objects.filter(IBAN=self.IBAN).exclude(user=self.user))>0:
Exception Type: AttributeError at /register-as-translator/
Exception Value: 'TranslatorRegistrationForm' object has no attribute 'IBAN'
Since you are validating the value of a single field iban, it would be better to define a clean_iban method instead of clean:
def clean_iban(self):
iban = self.cleaned_data['IBAN']
# Note using exists() is more efficient and pythonic than 'len() > 0'
if UserProfile.objects.filter(IBAN=iban).exists():
raise ValidationError('Invalid IBAN')
return iban
The clean method is meant for validating fields that depend on each other. If you override clean, you can't assume that a value will be in cleaned_data.
def clean(self):
cleaned_data = super(TranslatorRegistrationForm, self).clean()
if 'iban' in cleaned_data:
iban = cleaned_data['iban']
if len(UserProfile.objects.filter(IBAN=self.IBAN).exclude(user=self.user))>0:
raise ValidationError('Invalid IBAN')
return cleaned_data
Once you've called super(TranslatorRegistrationForm, self).clean(), you should be able to access the value of the IBAN field in cleaned_data['IBAN']. The attribute self.IBAN is a field definition, rather than the field's value.

Django: dynamic success_url results in "'NoneType' object has no attribute 'find'"

I would like to redirect the success_url to the same form after the form was submitted and valid. Online I found a description of a solution, however this solution and my other code option generate the same error message.
Exception Value: 'NoneType' object has no attribute 'find'
urls.py
url(r'^pictures/(?P<id>\d+)/$', PictureUpload.as_view(), name='picture_upload'),
...
1st views.py option
copies the existing link path
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = lambda self: self.request.path
2nd views.py option
recreates the link path based on the reverse url plus the id
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = reverse('picture_upload',
kwargs={'id': self.kwargs.get('id', None)})
Both options end up in the same traceback.
Request Method: POST
Request URL: http://127.0.0.1:8000/pictures/2/
Django Version: 1.5.1
Python Version: 2.7.1
Installed Applications:
('django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'picture',
'debug_toolbar')
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',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in post
165. return self.form_valid(form)
File "/Users/Development/project/apps/picture/picture_views.py" in form_valid
180. return super(PictureUpload, self).form_valid(form)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in form_valid
65. return HttpResponseRedirect(self.get_success_url())
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/http/response.py" in __init__
388. parsed = urlparse(redirect_to)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlparse
134. tuple = urlsplit(url, scheme, allow_fragments)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlsplit
173. i = url.find(':')
Exception Type: AttributeError at /pictures/2/
Exception Value: 'NoneType' object has no attribute 'find'
It looks like neither of your get_success_url implementations actually return the URL, so assuming that's not just a cut-and-paste error you're passing None to the HttpResponseRedirect.

saving inlineformset_factory data

#render_to('edit_operation.html')
def edit_operation(request, pk):
from forms import OpBaseForm, OperationForm
from django.forms.models import inlineformset_factory
op = Operation.objects.get(pk=pk)
OpBaseFormSet = inlineformset_factory(Operation, OpBase, form=OpBaseForm, extra=5, )
if request.method == "POST":
form = OperationForm(request.POST, instance=op)
formset = OpBaseFormSet(request.POST, instance=op)
if formset.is_valid() and form.is_valid():
form.save()
formset.save() #error here
return HttpResponseRedirect( op.get_absolute_url() )
else:
form = OperationForm(instance=op)
formset = OpBaseFormSet(instance=op)
return {'operation': op, 'opform': form, 'formset': formset}
This seems pretty straightforward, but whenever I try to submit data (even unchanged data), I get this error:
Environment:
Request Method: POST
Request URL: http://localhost:8000/edit/operation/1/
Django Version: 1.0.2 final
Python Version: 2.6.2
Installed Applications:
['main',
'django_extensions',
'django.contrib.comments',
'django.contrib.admindocs',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.gis',
'django.contrib.humanize',
'registration']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "/usr/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/dist-packages/annoying/decorators.py" in wrapper
55. output = function(request, *args, **kwargs)
File "/home/chris/Websites/jobmap/main/views.py" in edit_operation
68. formset.save()
File "/usr/lib/python2.6/dist-packages/django/forms/models.py" in save
389. return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "/usr/lib/python2.6/dist-packages/django/forms/models.py" in save_existing_objects
403. obj = existing_objects[form.cleaned_data[self._pk_field.name]]
Exception Type: KeyError at /edit/operation/1/
Exception Value: None
Anyone have any idea what is causing this error? If theres an error in the formset, then what is formset.is_valid() doing being 'True'? Anyone at least have any ideas on how to debug this in order to find whats going wrong? Both forms work perfectly fine when used individually, and I have {{formset.management_form}} in my template.
Just a quick guess... is your OpBaseForm excluding the model pk? Or, are you missing the pk field in your template? In other words, if you are laying out the fields yourself you still need to include the pk field even though it's hidden.