in my previous question how-to-save-many-to-many-relationship-in-django helped me about how to save many to many but i have some issue to save. Here we go..
I have the forloop template like
{% for items in store %}
<input type="checkbox" value="{{ items.id|safe }}" name="store[]">
{% endfor %
And the mission here is i am going to save many to many relation.
so
if request.method == 'POST':
...
new_track.save()
some_var = request.POST.getlist('store[]')
some_var giving me this [u'2', u'4', u'3']
new_store = Store.objects.filter(id__in=some_var)
pprint.pprint(new_store)
new_track.store.add(new_store)
new_store giving me this [<Store: Store object>, <Store: Store object>, <Store: Store object>]. Previously i tried with objects.get() that was working but saving multiple i come to use filter but don't know how to save multiple object. Now i have the error is
int() argument must be a string or a number, not 'QuerySet'
Updated:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/dashboard/track_info/10/
Django Version: 1.7
Python Version: 2.7.6
Installed Applications:
('django.contrib.sites',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dsp',
'frontend',
'ckeditor',
'social.apps.django_app.default')
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/ri/studio/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/home/ri/studio/Audiotube/dsp/decorators.py" in inner
46. return view(request, *args, **kwargs)
File "/home/ri/studio/Audiotube/dsp/views.py" in track_infodetail
338. new_track.store.add(new_store)
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in add
917. self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in _add_items
1010. '%s__in' % target_field_name: new_ids,
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/query.py" in filter
691. return self._filter_or_exclude(False, *args, **kwargs)
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
709. clone.query.add_q(Q(*args, **kwargs))
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
1287. clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
1314. current_negated=current_negated, connector=connector)
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
1181. lookups, value)
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in get_lookup_constraint
1550. root_constraint.add(lookup_class(Col(alias, targets[0], sources[0]), value), AND)
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/lookups.py" in __init__
82. self.rhs = self.get_prep_lookup()
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/lookups.py" in get_prep_lookup
85. return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup
648. return [self.get_prep_value(v) for v in value]
File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
915. return int(value)
Exception Type: TypeError at /dashboard/track_info/10/
Exception Value: int() argument must be a string or a number, not 'QuerySet'
add takes multiple objects as arguments. This should work
new_track.store.add(*new_store)
Django Documentation on Many-to-Many
new_store is a queryset, not a single object. Using the get() method will only return a single model object.
Instead, you must interact with each object in the queryset if you wish to use the same process that was working for get(). As such, you can use for each_store in new_store: new_track.store.add(each_store)
(Edited to get rid of conjecture; the above will work but there should be more performance-friendly ways to do this if that is a concern)
I suspect that the error is related to Django attempting to pass the pk of a single object for the add function, preparing the value as an integer before doing some database operation. Expecting an integer to find the field but instead getting passed the queryset object type spits out the error you see.
Related
I am trying to show stock records of a particular product. While passing id of that product to stock records, it is showing invalid literal for int() with base 10: 'Ice Cream' error.
My code looks like this:
models.py
class mProduct(models.Model):
mProduct_id=models.AutoField(primary_key=True)
mProduct_name=models.CharField(max_length=50)
mProduct_qtyunit =
models.ForeignKey(mProductUnit,on_delete=models.CASCADE) #Product
##Unit has one to many relationship with
##mProduct
mProduct_qty=models.FloatField(default=0) ##current stock
def __str__(self):
return self.mProduct_name
class mStock(models.Model):
mStock_id=models.AutoField(primary_key=True)
mStock_date=models.DateTimeField(default=timezone.now)
mStock_product=models.ForeignKey(mProduct,on_delete=models.CASCADE)
mStock_qty=models.FloatField()
views.py
In this view, I am trying to get object for a particular product and use it to get it's stock records through filter().
def mStockDetailView(request,id):
model=mStock
m=get_object_or_404(mProduct,mProduct_id=id)
stock=mStock.objects.filter(mStock_product=m.mProduct_name)
context={
'stock':stock,
}
return render(request,'dairyapp/stock-details.html',context)
template: productlist.html
I passed product id as parameter with url.
{% for p in product %}
<a href="{% url 'dairyapp:stock-detail' id=p.mProduct_id %}">
{{p.mProduct_name}}</a>
{%endfor%}
urls.py
path('stockrecords/<id>',views.mStockDetailView,name='stock-detail'),
Despite this, I am getting
invalid literal for int() with base 10: 'Ice Cream' error
Can anyone provide solution for this error?
Traceback:
Request Method: GET
Request URL: http://localhost:8000/stockrecords/5
Django Version: 2.1.3
Python Version: 3.6.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dairyapp.apps.DairyappConfig',
'widget_tweaks']
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 "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/media/coder/Multimedia/My Projects/Software/Dairy/Dairy Soft/dairy/dairyapp/views.py" in mStockDetailView
79. stock=mStock.objects.filter(mStock_product=m.mProduct_name)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in filter
844. return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in _filter_or_exclude
862. clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python3.6/dist-packages/django/db/models/sql/query.py" in add_q
1263. clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/sql/query.py" in _add_q
1287. split_subq=split_subq,
File "/usr/local/lib/python3.6/dist-packages/django/db/models/sql/query.py" in build_filter
1225. condition = self.build_lookup(lookups, col, value)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/sql/query.py" in build_lookup
1096. lookup = lookup_class(lhs, rhs)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/lookups.py" in __init__
20. self.rhs = self.get_prep_lookup()
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related_lookups.py" in get_prep_lookup
115. self.rhs = target_field.get_prep_value(self.rhs)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/__init__.py" in get_prep_value
965. return int(value)
Exception Type: ValueError at /stockrecords/5
Exception Value: invalid literal for int() with base 10: 'Ice Cream'
Based on the traceback I am quite certain the problem is on this line:
stock=mStock.objects.filter(mStock_product=m.mProduct_name)
You are attempting to get an mStock object by filtering on the foreign key that points to an mProduct object. You are using the keyword argument mStock_product so the value passed should refer to an mProduct. You are passing m.mProduct_name which is a string. Instead you should pass m.mProduct_id which is your reference to an mProject object. So, the new line should be:
stock = mStock.objects.filter(mStock_product=m.mProduct_id)
or you can let Django figure out the primary key and just pass the object like this (Thanks to A.L.Flanagan for pointing this out):
stock = mStock.objects.filter(mStock_product=m)
I'm using Cloudinary in my Django application to store and serve images that users upload in one view of my site. The images are getting uploaded and shown correctly; however, in my UpdateView when a user checks 'clear' to remove the previous image and then submits the form this error is shown:
TypeError: expected string or bytes-like object
The error page in the browser also shows these highlighted messages:
...\lib\site-packages\cloudinary\models.py in to_python
return self.parse_cloudinary_resource(value) ...
...\lib\site-packages\cloudinary\models.py in parse_cloudinary_resource
m = re.match(CLOUDINARY_FIELD_DB_RE, value) ...
...\AppData\Local\Programs\Python\Python36-32\lib\re.py in match
return _compile(pattern, flags).match(string)
These are what my model, view and form look like:
models.py:
class Item(models.Model):
name = models.CharField(max_length=255)
image1 = CloudinaryField('image', blank=True, null=True)
views.py
class ItemUpdateView(LoginRequiredMixin, UpdateView):
model = models.Item
form_class = forms.ItemForm
forms.py
class ItemForm(forms.ModelForm):
image1 = CloudinaryFileField(
required=False,
options = {'crop': 'limit', 'width': 546, 'height': 1000,})
class Meta:
model = models.Item
fields = ("image1", "name")
I think Cloudinary is still expecting something when the field's value is empty. I have looked at the docs and searched the web and I just can't figure out how to fix this.
Edit: I checked my admin and tried to edit an item from there and got the same error when I checked the 'clear' checkbox and hit Save. So it seems that the problem is with how I've created the image1 field on my model, since the Admin view would only be relying on that. But I still don't know how to fix it.
Edit2: Full Traceback of when I check 'clear' on the image field and click Save, from the admin:
Environment:
Request Method: POST Request URL:
http://127.0.0.1:8000/admin/items/item/4/change/
Django Version: 1.11.1 Python Version: 3.6.1 Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'cloudinary',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.twitter',
'haystack',
'items']
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
"D:\projects\django\gia\lib\site-packages\django\core\handlers\exception.py"
in inner
41. response = get_response(request)
File
"D:\projects\django\gia\lib\site-packages\django\core\handlers\base.py"
in _get_response
187. response = self.process_exception_by_middleware(e, request)
File
"D:\projects\django\gia\lib\site-packages\django\core\handlers\base.py"
in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\options.py"
in wrapper
551. return self.admin_site.admin_view(view)(*args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\utils\decorators.py"
in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\views\decorators\cache.py"
in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\sites.py"
in inner
224. return view(request, *args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\options.py"
in change_view
1511. return self.changeform_view(request, object_id, form_url, extra_context)
File
"D:\projects\django\gia\lib\site-packages\django\utils\decorators.py"
in _wrapper
67. return bound_func(*args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\utils\decorators.py"
in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File
"D:\projects\django\gia\lib\site-packages\django\utils\decorators.py"
in bound_func
63. return func.get(self, type(self))(*args2, **kwargs2)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\options.py"
in changeform_view
1408. return self._changeform_view(request, object_id, form_url, extra_context)
File
"D:\projects\django\gia\lib\site-packages\django\contrib\admin\options.py"
in _changeform_view
1440. if form.is_valid():
File "D:\projects\django\gia\lib\site-packages\django\forms\forms.py"
in is_valid
183. return self.is_bound and not self.errors
File "D:\projects\django\gia\lib\site-packages\django\forms\forms.py"
in errors
175. self.full_clean()
File "D:\projects\django\gia\lib\site-packages\django\forms\forms.py"
in full_clean
386. self._post_clean()
File "D:\projects\django\gia\lib\site-packages\django\forms\models.py"
in _post_clean
396. self.instance.full_clean(exclude=exclude, validate_unique=False)
File
"D:\projects\django\gia\lib\site-packages\django\db\models\base.py" in
full_clean
1226. self.clean_fields(exclude=exclude)
File
"D:\projects\django\gia\lib\site-packages\django\db\models\base.py" in
clean_fields
1268. setattr(self, f.attname, f.clean(raw_value, self))
File
"D:\projects\django\gia\lib\site-packages\django\db\models\fields__init__.py"
in clean
601. value = self.to_python(value)
File "D:\projects\django\gia\lib\site-packages\cloudinary\models.py"
in to_python
74. return self.parse_cloudinary_resource(value)
File "D:\projects\django\gia\lib\site-packages\cloudinary\models.py"
in parse_cloudinary_resource
50. m = re.match(CLOUDINARY_FIELD_DB_RE, value)
File
"C:\Users\samee\AppData\Local\Programs\Python\Python36-32\lib\re.py"
in match
172. return _compile(pattern, flags).match(string)
Exception Type: TypeError at /admin/items/item/4/change/ Exception
Value: expected string or bytes-like object
Maybe a bit late here but I had the same issue and in my search for a solution I stumbled upon this.
What I worked out was that the validation method was still looking for a object that no longer existed. By clicking the clear button you effectively remove it from the post back. Validation is set up by default to flag this up because it is trying to clea (validate) something that is now no longer there.
You get around it quite easily. Simply create the clean method that the is_valid method invokes. The picture wont be there anymore so just return None. Here is a code example:
From my is_valid():
if request.method == 'POST':
if picture_form_set.is_valid():
which in turn calls the clean methods, so create one for the Cloudaniry field:
def clean_picture(self):
return self.cleaned_data['picture'] or None
Hope that helps
The issue is with the to_python method in the the CloudinaryField, it expects the value of image to a none but instead gets a False.
Solution create a new field that inherits from the parent CloudinaryField apply the fix and use that as your models field.
Solution by Marco Silva on this github issue, https://github.com/cloudinary/pycloudinary/issues/98.
class CloudinaryFieldFix(CloudinaryField):
def to_python(self, value):
if value is False:
return value
else:
return super(FixCloudinaryField, self).to_python(value)
I'm using DRF and be front of AttributeError 'str' object has no attribute '~~'.
my error page and code
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/
Django Version: 1.9.7
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'blog',
'account',
'taggit',
'friendship',
'rest_framework']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/decorators.py" in handler
52. return func(*args, **kwargs)
File "/home/keepair/djangogirls/blog/views.py" in post_list
37. return Response(serializer.data)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
700. ret = super(ListSerializer, self).data
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
239. self._data = self.to_representation(self.instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in <listcomp>
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
463. attribute = field.get_attribute(instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/relations.py" in get_attribute
157. return get_attribute(instance, self.source_attrs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/fields.py" in get_attribute
83. instance = getattr(instance, attr)
Exception Type: AttributeError at /blog/
Exception Value: 'str' object has no attribute 'author'
I wonder how to make serializers.py codes.
I already studied : http://www.django-rest-framework.org/api-guide/relations/
But I don't understand what I should do. Where should I put serializers.py?
And how to make my serializers code? Or maybe models.ForienKey is unavailable on using DRF?
blog/views.py
#api_view(['GET'])
def post_list(request, format=None):
"""
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
lat = request.POST.get('user_lat', '13')
lon = request.POST.get('user_lon', '15')
userpoint = GEOSGeometry('POINT(' + lat + ' ' + lon + ')', srid=4326)
i=1
while i:
list_i = Post.objects.filter(point__distance_lte = (userpoint, D(km=i)))
list_total = str(',' + ' list_i')
post_list = list(chain(list_total))
if len(post_list) >= 0 :
break
serializer = PostSerializer(post_list, many=True)
return Response(serializer.data)
This has nothing to do with your serializer, or where you put it. The error traceback is telling you that the error happens in the view.
So, in your post_list view, you build up a list (also called post_list) which is populated by a list of strings. Then you try and put it through the PostSerializer, which of course is expecting a queryset of Posts.
I'm not sure what the point of the list is; seems like you should be passing the Posts directly to the serializer.
Trying to create an object with get_or_create(). The response hits, but it never successfully creates the object.
Python code:
class Note(models.Model):
user = models.ForeignKey(User)
topic = models.CharField(max_length=500, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
content = models.TextField(null=True, blank=True)
type = models.ForeignKey(NoteType, null=True, blank=True)
def __unicode__(self):
return self.topic
def post(request):
topic = request.POST['topic']
user = request.user
content = request.POST['content']
note_type = request.POST['type']
note, created = Note.objects.get_or_create(user=user, topic=topic, content=content, type=note_type)
return HttpResponseRedirect('/home/')
So the exception constantly hits and never creates the object. Urls are fine and I'm importing the model. Any reason why this object isn't being created? Theres no errors, it just redirects as normal.
traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/post/
Django Version: 1.5.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'notes')
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:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "c:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "c:\Users\Alana\project-fridge\notes\views.py" in post_note
34. note, created = Note.objects.get_or_create(user=user, topic=topic, content=content, type=note_type)
File "c:\Python27\lib\site-packages\django\db\models\manager.py" in get_or_create
146. return self.get_query_set().get_or_create(**kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py" in get_or_create
470. return self.get(**lookup), False
File "c:\Python27\lib\site-packages\django\db\models\query.py" in get
379. clone = self.filter(*args, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py" in filter
655. return self._filter_or_exclude(False, *args, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
673. clone.query.add_q(Q(*args, **kwargs))
File "c:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
1266. can_reuse=used_aliases, force_having=force_having)
File "c:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_filter
1197. connector)
File "c:\Python27\lib\site-packages\django\db\models\sql\where.py" in add
71. value = obj.prepare(lookup_type, value)
File "c:\Python27\lib\site-packages\django\db\models\sql\where.py" in prepare
339. return self.field.get_prep_lookup(lookup_type, value)
File "c:\Python27\lib\site-packages\django\db\models\fields\related.py" in get_prep_lookup
143. return self._pk_trace(value, 'get_prep_lookup', lookup_type)
File "c:\Python27\lib\site-packages\django\db\models\fields\related.py" in _pk_trace
216. v = getattr(field, prep_func)(lookup_type, v, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_lookup
322. return self.get_prep_value(value)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
555. return int(value)
Exception Type: ValueError at /post/
Exception Value: invalid literal for int() with base 10: 'text'
Thank you for your help in advance.
I assume that you are storing a list of various Note Types in the NoteType model...
To make this code work, you are first going to need to get one of them from that model and then set use that when creating your new note
note_type = request.POST['type']
note_type_orm = NoteType.objects.get(type=note_type)
note, created = Note.objects.get_or_create(user=user, topic=topic, content=content, type=note_type_orm)
Notice the change in the get_or_create that I am now using the note_type_orm and not just the note_type (which is just a string)
I have url like this http://gagandeepdesk/2690/ which I am filtering with urls.py file and sending 2690 as one of the parameters to the function.
my urls.py filter looks like this,
url(r'^(\d+)/', 'scango.scanner.views.download'),
And that function looks like this,
def download(request, MediaId):
media = Media.objects.get(id=int(MediaId))
#print media
return HttpResponse(FileIterWrapper(open(media.path)))
I am getting error 'too many values to unpack' on line
media = Media.objects.get(id=int(MediaId))
I also tried running this function standalone without request object and it is running perfectly fine. So, I am confused what I have done wrong here.
Environment:
Request Method: GET
Request URL: http://gagandeepdesk/2690/
Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['haystack',
'scanner',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin']
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:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\gagasing\Desktop\ideas\scango\..\scango\scanner\views.py" in download
21. media = Media.objects.get(id=int(MediaId))
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in get
132. return self.get_query_set().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
343. clone = self.filter(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
552. return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
570. clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
1170. can_reuse=used_aliases, force_having=force_having)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_filter
1013. arg, value = filter_expr
Exception Type: ValueError at /2690/
Exception Value: too many values to unpack
(r'^(?P<MediaId>\d+)/$', 'scango.scanner.views.download')
Maybe try this instead?
This is an example of named groups.
In Python regular expressions, the syntax for named regular expression
groups is (?Ppattern), where name is the name of the group and
pattern is some pattern to match.