So I got a method in views.py that checks if a certain product is saved in the session variables. If this is the case then it will look up the ID of the product in mongodb in order to filter a queryset on a few attributes of this product. I have the following code:
def moederbordenComp(request,objectlijst):
objectlijst_filtered = objectlijst
if "processorenid" in request.session:
processor= Processoren.objects.get(id=request.session["processorenid"])
objectlijst_filtered = objectlijst.filter(Socket__icontains=processor.Socket)
if "behuizingenid" in request.session:
behuizing = Behuizingen.objects.get(id=request.session["behuizingenid"])
objectlijst_filtered = objectlijst.filter(Form_Factor__icontains=behuizing.Form_Factor)
if "geheugenid" in request.session:
geheugen = Geheugen.objects.get(id=request.session["geheugenid"])
objectlijst_filtered = objectlijst.filter(Geheugentype__icontains=geheugen.Geheugentype)
objectlijst_filtered = objectlijst.filter(Geheugentype__icontains=geheugen.Aantal)
if "hardeid" in request.session:
harde = Harde.objects.get(id=request.session["hardeid"])
objectlijst_filtered = objectlijst.filter(Hardeschijf_bus__icontains=harde.Hardeschijf_bus)
return objectlijst_filtered
So basically. If processorenid exists then filter the queryset called "objectlist" so that only the motherboards remain that contain the processor.Socket.
Now for the real issue:
whenever I remove the objectlijst_filtered and just return the objectlijst (so unfiltered, without doing anything) everything works fine. However if I try to return and then use objectlijst_filtered or even print objectlijst_filtered it raises the following error:'list' object has no attribute 'join'
This is the complete error traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/moederborden/
Django Version: 1.7
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'pcbuilder')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/robin/Work/School/A-Pc/Website/pcbuilder/views.py" in moederborden
728. moederbordenlijst = compatibility(request,moederbordenlijst)
File "/home/robin/Work/School/A-Pc/Website/pcbuilder/compatibility.py" in compatibility
6. objectlijst_filtered = moederbordenComp(request,objectlijst)
File "/home/robin/Work/School/A-Pc/Website/pcbuilder/compatibility.py" in moederbordenComp
34. print objectlijst_filtered
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/queryset.py" in __repr__
58. self._populate_cache()
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/queryset.py" in _populate_cache
93. self._result_cache.append(self.next())
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py" in next
1137. raw_doc = self._cursor.next()
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py" in _cursor
1182. self._cursor_obj = self._collection.find(self._query,
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py" in _query
1215. self._mongo_query = self._query_obj.to_query(self._document)
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/visitor.py" in to_query
92. query = query.accept(QueryCompilerVisitor(document))
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/visitor.py" in accept
157. return visitor.visit_query(self)
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/visitor.py" in visit_query
80. return transform.query(self.document, **query.query)
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/transform.py" in query
87. value = field.prepare_query_value(op, value)
File "/usr/local/lib/python2.7/dist-packages/mongoengine/fields.py" in prepare_query_value
106. value = re.escape(value)
File "/usr/lib/python2.7/re.py" in escape
214. return pattern[:0].join(s)
Exception Type: AttributeError at /moederborden/
Exception Value: 'list' object has no attribute 'join'
Any help would be greatly appreciated. I've used the filter method in several other parts of the project without any issues so I'm at a loss.
Thanks in advance.
Related
For my API, I have to find out to what projects a user has access to, and return them. I try to do this like so:
def get_queryset(self):
user = self.request.user
allow_all = user.is_superuser or user.is_staff or settings.API_UNSAFE
if self.action == 'list' and not allow_all:
projects = Project.objects.all()
user_projects = Project.objects.none()
for project in projects:
permission = Permission.objects.filter(user=user.user, table_name='Project', fk=project.id)
if permission.count() > 0:
user_projects = user_projects | project
return user_projects
return Project.objects.all()
Which results in:
'Project' object is not iterable
So I used values() instead of all(). But when you use .values it's no longer possible to concat the instance with a queryset. Meaning I have to query the same project twice, resulting in this hacky approach:
projects = Project.objects.values()
user_projects = Project.objects.none()
for project in projects:
permission = Permission.objects.filter(user=user.user, table_name='Project', fk=project['id'])
if permission.count() > 0:
# Wanted to use .get() here, but that threw the same error
user_project = Project.objects.filter(id=project['id'])
user_projects |= user_project
return user_projects
Surely there is a better way, what am I doing wrong?
Stacktrace:
Environment:
Request Method: GET
Request URL: http://localhost:8000/api/projects/
Django Version: 2.0.6
Python Version: 3.7.0
Installed Applications:
['apps.api',
'rest_framework',
'apps.dashboard',
'apps.login',
'apps.base',
'sass_processor',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_seed',
'rest_framework.authtoken']
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 "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/rest_framework/viewsets.py" in view
95. return self.dispatch(request, *args, **kwargs)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
494. response = self.handle_exception(exc)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
454. self.raise_uncaught_exception(exc)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
491. response = handler(request, *args, **kwargs)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/rest_framework/serializers.py" in data
742. ret = super(ListSerializer, self).data
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/Users/Ruben/Documents/Projects/BIM_Github/bim-data-manager/venv/lib/python3.7/site-packages/rest_framework/serializers.py" in to_representation
660. self.child.to_representation(item) for item in iterable
Exception Type: TypeError at /api/projects/
Exception Value: 'Project' object is not iterable
The error has nothing at all to do with accessing the project ID.
The result of | between an empty queryset and an instance is the instance. So this means that when your permission exists, your user_projects variable becomes a single instance; then, later, the serializer fails as it is expecting a queryset.
You've already got a better way of doing this in a single query, but for reference if you did want to build up a list like this the better way would be to accumulate the IDs and then get them all in one query at the end; or, simply append the instances to a list.
I had a problem with my Django program. I'm a beginner in Django, I was looking for an answer with different posts with the same error than mine but no success ...
Here's my traceback :
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/pod
Django Version: 1.11.2
Python Version: 2.7.13
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'labinit',
'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 "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\django_learneo3\Learneo\labinit\views.py" in groupe_pod
121. if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
183. return self.is_bound and not self.errors
File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
175. self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
384. self._clean_fields()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
396. 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
639. getter = data.get
Exception Type: AttributeError at /pod
Exception Value: 'unicode' object has no attribute 'get'
This issue appears since I have changed my init fonction, for the form that I use in my view :
Forms:
class Groupe_Form(forms.ModelForm) :
def __init__(self, nom_groupe, *args, **kwargs):
super(Groupe_Form,self).__init__(*args, **kwargs)
self.fields['pod'].widget = forms.Select()
pod1 = Groupe.objects.filter(nom_groupe = nom_groupe).values_list('pod', flat = True)
pods = list(pod1)
self.fields['pod'].queryset = Pod.objects.filter(id__in=pods)
class Meta:
model = Groupe
fields = ['pod']
Views :
def groupe_pod(request):
global new_groupe
grp = new_groupe
form = forms.Groupe_Form(request.POST, grp)
if request.method == 'POST':
if form.is_valid():
print "form was valid"
data_groupe_pod = request.POST.get('grp_pod')
print "data_groupe :", data_groupe_pod
global new_cours
print new_cours
if new_cours == "ICND1":
return redirect('http://127.0.0.1:8000/icnd_1')
elif new_cours == "ICND2":
return redirect('http://127.0.0.1:8000/icnd_2')
else :
form = forms.Groupe_Form(new_groupe)
return render(request, 'pod.html', locals())
I've tried many things, I really don't know where is the problem in my Django code.
Your form's __init__ method is:
def __init__(self, nom_groupe, *args, **kwargs):
Therefore you should instantiate it with:
form = forms.Groupe_Form(grp, request.POST)
You currently have the arguments the other way round.
Your __init__ signature has as its first parameter nom_groupe. In form = forms.Groupe_Form(request.POST, grp) you pass request.POST as the first parameter. You have to switch the parameters:
form = forms.Groupe_Form(grp, request.POST)
So I am trying to use django-excel: https://github.com/pyexcel/django-excel
and just simply export a certain model into xls. I set up the settings according to the documentation, but I got this error when running:
Exception at /calbase/export/sheet
Unexpected data type <class 'django.db.models.fields.files.FieldFile'>
Here is my views:
def export_data(request, atype):
if atype == "sheet":
return excel.make_response_from_a_table(
Equipment, 'xls', file_name="sheet")
elif atype == "book":
return excel.make_response_from_tables(
[Equipment, Calibration], 'xls', file_name="book")
elif atype == "custom":
equipment = Equipment.objects.get(slug='ide')
query_sets = Choice.objects.filter(equipment=equipment)
column_names = ['choice_text', 'id', 'votes']
return excel.make_response_from_query_sets(
query_sets,
column_names,
'xls',
file_name="custom"
)
else:
return HttpResponseBadRequest(
"Bad request. please put one of these " +
"in your url suffix: sheet, book or custom")
and when I tried to go
http://127.0.0.1:8000/calbase/export/sheet
it gives me the exception above.
By the way is there any good example using django-excel? I can't seem to run the one provided
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/calbase/export/sheet
Django Version: 1.10
Python Version: 3.5.2
Installed Applications:
['calbase.apps.CalbaseConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'haystack',
'whoosh',
'carton']
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 "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\views.py" in export_data
97. Equipment, 'xls', file_name="sheet")
File "C:\Users\hansong.li\Documents\GitHub\equipCal\django_excel\__init__.py" in make_response_from_a_table
147. file_name=file_name, **keywords)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel_webio\__init__.py" in make_response
244. file_stream = pyexcel_instance.save_to_memory(file_type, None, **keywords)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel\sheets\sheet.py" in save_to_memory
114. self.save_to(out_source)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel\sheets\sheet.py" in save_to
79. source.write_data(self)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel\sources\file_source_output.py" in write_data
86. sheet, **self.keywords)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel\sources\renderer\_excel.py" in render_sheet_to_stream
35. **keywords)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel_io\io.py" in save_data
70. **keywords)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel_io\io.py" in store_data
91. writer.write(data)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel_io\book.py" in write
177. sheet_writer.write_array(incoming_dict[sheet_name])
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel_io\sheet.py" in write_array
82. self.write_row(row)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyexcel_xls\xls.py" in write_row
230. self.native_sheet.write(self.current_row, i, value)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\xlwt\Worksheet.py" in write
1033. self.row(r).write(c, label, style)
File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\xlwt\Row.py" in write
263. raise Exception("Unexpected data type %r" % type(label))
Exception Type: Exception at /calbase/export/sheet
Exception Value: Unexpected data type <class 'django.db.models.fields.files.FieldFile'>
I have a very basic 'Place' model:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
and I'm trying to review it using the app: https://github.com/diefenbach/django-reviews
When trying to add a review to certain Place object, in the app's views https://github.com/diefenbach/django-reviews/blob/master/reviews/views.py, it reaches te 'save' method and actually saves a record in the database. However it raises the following TypeError:
Environment:
Request Method: POST
Request URL: http://ec2-54-77-118-44.eu-west-1.compute.amazonaws.com:5000/reviews/add/11/1
Django Version: 1.6.5
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'places',
'reviews')
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/ubuntu/webapps/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
199. response = middleware_method(request, response)
File "/home/ubuntu/webapps/local/lib/python2.7/site-packages/django/contrib/sessions/middleware.py" in process_response
38. request.session.save()
File "/home/ubuntu/webapps/local/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in save
57. session_data=self.encode(self._get_session(no_load=must_create)),
File "/home/ubuntu/webapps/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in encode
87. serialized = self.serializer().dumps(session_dict)
File "/home/ubuntu/webapps/local/lib/python2.7/site-packages/django/core/signing.py" in dumps
88. return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/lib/python2.7/json/__init__.py" in dumps
250. sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py" in encode
207. chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py" in iterencode
270. return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py" in default
184. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /reviews/add/11/1
Exception Value: <Place: Teteria India> is not JSON serializable
I don't understand why this error raises if I'm still not using any AJAX or JSON and as far as I could see neither does the reviews app's views. Does it have anything to do with the forms?
And anyway, how can it be that a model with only one CharField is not JSON serializable? Do I have to provide the serialization?
Thanks!
In the line 148, it store object in the session
request.session["last-rated-object"] = object
then perfoms a redirect to reviews_thank_you's view
def thank_you(request, template_name="reviews/thank_you.html"):
"""Displays a thank you page.
"""
if request.session.has_key("last-rated-object"):
object = request.session.get("last-rated-object")
del request.session["last-rated-object"]
else:
object = None
return render_to_response(template_name, RequestContext(request, {
"object" : object,
}))
It is returning the object without serialize it and i think here is the problem. Can you edit that view to return a serialize version of you object?
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.