django when edit the data from data base - django

i am tryong to edit the data from database i am getting error at update_user_id for more info please look at this link then u will understood please
http://www.pastie.org/1301839

It seems that you didn't set the update_user_id key in your session. You can work around this problem using exceptions:
try:
update_user_id = request.session["update_user_id"]
except KeyError:
update_user_id = SOME_DEFAULT_VALUE
Or (even better) by using request.session.get:
update_user_id = request.session.get("update_user_id", SOME_DEFAULT_VALUE)
The two snippets are equivalent.

From your traceback:
Exception Type: KeyError at /institutes_admin/
Exception Value: 'update_user_id'
A KeyError means that you tried to get something from a dictionary using a dictionary key that didn't exist. This looks like the problem (from further up the traceback):
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/epw/admin_views.py" in institutional_ip_admin
604. update_user_id = request.session['update_user_id']
A solution would be to provide a default value.

Related

TypeError: expected string or bytes-like object User.id

I'm trying to register an new Transaction object on the DB using Django, but I'm having TypeError: expected string or bytes-like object when I try to do user_id = user.id I can't really understand why this is happening, since I do the same steps when registering a new Bank object (as shown on prints below). I've tried to debug and the local variables have the correct value, I've also tried to cast user.id with string or int, but none of them worked.
traceback console error create Transaction method create Bank method
models.py
Firstly, please don't post code or errors as images; they are text, they should be posted as text in the question.
However I don't see anything in any of those snippets that suggest the error is with the user - that line is probably highlighted because it's the last in that multi-line call.
Rather, the error looks to be in the reference to date.today - if that's the datetime.date class, then today is a method, which you would need to call:
Transaction.objects.create(date=date.today(), ... )
Or, since that field has a default anyway, you could leave out the date attribute from the create call altogether.

why is Django MultipleObjectsReturned Error hogging memory?

I am using Django 1.9.10:
I have a model called Details has a unique_id column which is indexed:
try:
detail = Detail.objects.get(unique_id=UUID)
except MultipleObjectsReturned as m:
logger.error("uuid {} returned multiple objects - {}".format(UUID, str(m)))
Due to some error in code UUID=None this resulted in MultipleObjectsReturned error getting raised. but we noticed that almost 2-GB of memory is getting used up and it is slowing the system down a lot.
On printing str(m) in the error logs we found following error
MultipleObjectsReturned: get() returned more than one Details -- it returned 451424!
My Question is why is Django fetching so much data in memory just to raise an error? Django can just fetch the count?
I know I can use filter() to over come this issue but I am just surprised by this and want to understand why django is doing this?
Because that's how it's done internally:
def get(self, *args, **kwargs):
"""
Perform the query and return a single object matching the given
keyword arguments.
"""
clone = self.filter(*args, **kwargs) # calling `filter()` inside
if self.query.can_filter() and not self.query.distinct_fields:
clone = clone.order_by()
num = len(clone)
if num == 1:
return clone._result_cache[0]
if not num:
raise self.model.DoesNotExist(
"%s matching query does not exist." %
self.model._meta.object_name
)
raise self.model.MultipleObjectsReturned(
"get() returned more than one %s -- it returned %s!" %
(self.model._meta.object_name, num)
)
See the full source here.
I guess you wonder why it can't just fetch the number? Because it will make two requests to the database instead of one. One request to fetch the count and one request to fetch the data.
How can you fix it? You may change your application logic to avoid this situation. Assert that UUID is not None. Or fetch count before making an actual query.
Docs about get: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-a-single-object-with-get
Because you use .get when you know you shouldn't get multiple objects.
Choosing to use it in a case where 451424 items are returned instead isn't something it was designed for.
Because you have more then one with same ID in database.
Rewrite your query to this: Detail.objects.filter(unique_id=UUID)

haystack SearchQuerySet() is returning list instead of SearchQuerySet object

this is my get_queryset(): method in the view
def get_queryset(self):
#by here the search query is getting executed
self.vendor_filter=self.request.GET.get('select_vendor', 'all')
self.search_query=self.request.GET.get('q', "")
self.sort_by=self.request.GET.get('sort_by', "relevance")
queryset=SearchQuerySet().all()[:50]
return queryset
this method is throwing 'list' object has no attribute 'all' error. However I ran this SearchQuerySet().all() in django shell it is returning correct results.
.
it is very annoying issue. I dont know what is the mistake?, I am using whoosh with django-haystack search.
I found the reason why, the code queryset=SearchQuerySet().all()[:50] was converting the SearchQuerySet object to list. I changed it to queryset=SearchQuerySet().all() now it works as expected. It took me whole day to figure out. But still I don't know why it was doing that without throwing an exception or error.

Django MongoDB Queryset can't print or iterate

I try to execute a MongoDB raw query in Django of the type:
queryset= ObjectClass.objects(__raw__={ })
if I want to print the queryset or iterate I get the following error message:
"error_message": "cannot convert value of type <class 'mongoengine.queryset.QuerySet'> to bson",
Any suggestions why this happens, I couldn't find a suitable answer so far, thanks for any hints
Jonas
just a shot into the dark since I m not able to try it out by myself in the moment, since I uninstalled mongodb. But in the back of my mind I remember that I had a similar problem.
Try:
queryset= list(ObjectClass.objects(__raw__={ }))
for result in queryset:
print result

Django error: 'QueryDict' object has no attribute '_meta'

I am very new to django so this is probably a noob question.
I am trying to reuse django admin's change list view. I've created a admin model and want to provide the changelist template a list of these objects. In my view I have:
def placements(request):
partner_id = request.session.get('partner_id', 0)
self = PlacementAdmin(request.GET, Placement.objects.filter(partner=partner_id))
return render_to_response('publisher/placement/change_list.html', {'cl': self})
I get this error when I try to hit this function from a browser:
'QueryDict' object has no attribute '_meta'
Could anyone tell me what the error is or provide an easier way to accomplish this in case I am on the wrong track completely.
Heres the complete trace:
Request Method: GET
Request URL: http://localhost:8080/publisher/
Django Version: 1.3 beta 1
Exception Type: AttributeError
Exception Value:
'QueryDict' object has no attribute '_meta'
Exception Location: /Users/imran/django_env/lib/python2.6/site-packages/django/contrib/admin/options.py in __init__, line 278
Python Executable: /Users/imran/django_env/bin/python
Python Version: 2.6.1
Python Path:
['.',
'.',
'/Users/imran/Workspaces/publisher/django/pub_admin',
'/Users/imran/django_env/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg',
'/Users/imran/django_env/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg',
'/Users/imran/django_env/lib/python26.zip',
'/Users/imran/django_env/lib/python2.6',
'/Users/imran/django_env/lib/python2.6/plat-darwin',
'/Users/imran/django_env/lib/python2.6/plat-mac',
'/Users/imran/django_env/lib/python2.6/plat-mac/lib-scriptpackages',
'/Users/imran/django_env/Extras/lib/python',
'/Users/imran/django_env/lib/python2.6/lib-tk',
'/Users/imran/django_env/lib/python2.6/lib-old',
'/Users/imran/django_env/lib/python2.6/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Users/imran/django_env/lib/python2.6/site-packages']
It's best to post the traceback error when posting a question!
That said, the error comes from you passing request.GET to a ModelAdmin admin object which isn't expecting it.
You have a long road of troubles ahead of you though, as you're trying to use the magical change_list view template which is operated on by a collection of even more magical, undocumented template tags, which just doesn't normally appear in the same sentence as new to django.
I think you're on the wrong track simply because django's admin is not easy to hack into.
At a minimum, you'd have to pass in your template a ChangeList object for the cl variable.
If you really want to do this, the only advice I can give is to take a look at django.contrib.admin.options.ModelAdmin.changelist_view() since that's what you're trying to replicate.
Seriously though I'd like to talk you out of this. Django's actually really fun to work with!