Django 1.5 Admin - Object matching query does not exist - intermittent - python

Python 2.7.3
Django Version is 1.5
I am using the standard Django Admin DefaultModelAdmin for adding and changing objects.
Problem
When I add an object using Django Admin Add View - about one in every ten times - I get this error:
Object matching query does not exist> Lookup parameters were {'objectid_exact':234}
Instead, Django should just return to the Paginated List View where all objects can be seen - but it seems cannot find the newly created object.
Note - I have DEBUG enabled here - otherwise I see a standard error 500 page.
The line of code it complains about is on my models.py class:
From models.py:
return "MyObject: %s: %s (by: %s)" % (self.pk, self.title, self.namelc)
The thing is, if I refresh the Django Admin the object has been added and there are no problems with it.
I did some research around this and found some articles and tried out recommendations - but they made no difference - for example:
Django matching query does not exist after object save in Celery task
Finally - I added this line of code to the end of the svae_model() method and it solved the problem:
my_list = list(models.MyObject.objects.all())
I am not sure why this solves the issue - it forces Django to re-evaluate the QuerySet as per these articles:
Django lazy QuerySet and pagination
https://docs.djangoproject.com/en/1.5/ref/models/querysets/
There is no performance impact and so far, I have not seen the issue again.
I do no fully understand why this solves the issue so I would be grateful for any insights as to:
Why this work around seems to solve the issue?
Any insights as to the cause of the issue in the first place?
I am using #transaction.commit_on_success in the method that adds the item to DB - but as I said I think the issue is when Django tries to display the paginated List screen - it cannot find the newly created object.
Thanks in advance for any help - much appreciated!

Related

Deleting post from database using SQLAlchemy gives error: "Object '...' is already attached to session"

I'm trying to delete posts from a database using the posts ID but I keep getting the following error.
sqlalchemy.exc.InvalidRequestError: Object '' is already attached to session '34' (this is '35').
What im trying to do should be very simple but I've not used SQLAlchemy enough to be sure of what this means and how to fix it.
I have a route to delete the post that looks like this:
#app.route('/delete_post')
def delete_post():
post_id = request.args.get('post_id')
deleted_post = posts.query.filter_by(id=post_id).first()
db.session.delete(deleted_post)
db.session.commit()
flash('Post deleted!', 'success')
return redirect(url_for('admin_posts'))
All the route is supposed to do is get the post_id variable from the URL passed from the previous page, queries the database to find all posts that have an id of post_id and delete the matching post. I just keep getting the error I posted above.
I don't think the problem lies in the code, it should be working according to my understanding. I think the problem is something to with the SQLAlchemy db.sessions and that I have misused it somehow.
I should also note that I have used SQLAlchemy many times in the rest of the app for the creating of posts, replies and accounts and they all work. The issue is just with this.
I believe you are unintentionally creating 2 sessions, and sticking the same object into both sessions.
This line here
posts.query.filter_by(id=post_id).first()
Is most likely using one session (it's difficult to say w/o this model code).
Then
db.session.delete(deleted_post)
is likely using a different session.
The solution is to use the same session for both operations.
Try importing the session the posts model uses from the module it is in.
So I got it working, the problem was with my imports...
I'm not sure why or more importantly HOW this was the case but, I didn't correctly import from my init.py in my routes.py.
I had:
from app import app
But needed:
from app import app, db
Obvious and silly mistake, but I thought everything was working fine since all of my other SQLAlchemy features were working such as inserting and querying... very strange.

Django superuser doesn't have permission to delete models

I am working on upgrading a Django website from Django 1.8 to Django 2.2 and have come across a problem when trying to delete an object from the Django admin changelist view. When I try to delete an object, I am shown a screen with the words "Deleting the selected Records would result in deleting related objects, but your account doesn't have permission to delete the following types of objects". The problem is, I am a superuser and should have permission to delete any object I want, or so I thought.
I have read a decent amount of documentation on Django upgrades and permissions of superusers, however I haven't stumbled across anything that helps me (I could be missing something though). I have tried creating a new superuser just in case, still the same message occurs though. Anyway, Does anyone have any idea why this could be happening?
Note: I can't show any code because I am working for a company and I signed an NDA. Just some help pointing me in the right direction would be appreciated.
For anyone else who stumbles across this problem, dirkgroten was right and it turns out the has_delete_permission was overridden! Thanks for your help dirkgroten!
OPENEDX If You are facing This issue then do this thing from the backend.
Cannot delete user
Deleting the selected user would result in deleting related objects, but your account doesn't have permission to delete the following types of objects:
course enrollment
Open Mysql In EDX server like AWS
then
get user id based on username
then student_courseenrollment delete from this user
Example
select id from auth_user where username = 'exampleusername'
delete from student_courseenrollment where user_id = get user_id from 1 query set;
like delete from student_courseenrollment where user_id = 123;

In upgrading to Django 1.8, why do I get the AttributeError 'ManyToManyRel' object has no attribute 'rel'?

I'm going through and checking the various pages in our project, and the great majority appear to be working fine after the upgrade. However, when I try to view a particular entry in the admin, I get this error. On viewing the stack trace, everything is being done internally within Django's admin code, so there is no place in my own code that I can go to debug. This would suggest either that there is something wrong with the Django admin or that there is some release note I missed that is necessary to make this work properly. Any ideas? The actual error is happening here:
site-packages/django/contrib/admin/helpers.py in contents, line 206
if isinstance(f.rel, ManyToManyRel) and value is not None:
result_repr = ", ".join(map(six.text_type, value.all()))
else:
result_repr = display_for_field(value, f)
Obviously, I could go into Django and hack around, but I shouldn't have to do this on a new installation. Any help on pinpointing the issue would be much appreciated. I'm just staring t the screen at this point.
Was responding to Alasdair's comment and got to playing with our admin code, and I was able to narrow it down to the method call that was causing the error.
We have a Lead model that relates to our Company model via a ManyToManyField (i.e. one lead can be for one or more companies). The field that relates Lead to Company has a related_name of "leads".
class Company(models.Model):
...
class Lead(models.Model):
companies = models.ManyToManyField(Company, blank=True, related_name='leads')
...
The CompanyAdmin, looks like the following:
class CompanyAdmin(admin.ModelAdmin):
...
readonly_fields = 'leads',
...
def leads(self, obj):
...
So what appears to have been happening was, when we were trying to access the leads method from CompanyAdmin, Django was instead trying to access the company's Lead objects via the related name -- the ManyToManyField that was throwing the error. I resolved the conflict by changing the method name in the admin to "my_leads".
Looks like something was changed somewhere between 1.8 and the final version of 1.6 that has opened the door to potential conflict between related names and admin methods. The solution, make sure there is no overlap in naming, and things should work fine.

Using django filters

I'm new to django so this must be a silly question but i was working my way through the official documentation tutorial(the one about a site with polls and choices) and i wanted to filter out polls with no choices, i managed to do that with a filter in the queryset argument of the ListView:
queryset=Poll.objects.filter(pub_date__lte=timezone.now).filter(id__in=Choice.objects.all).order_by('-pub_date')[:5]
And this indeed filters the query, the problem is that if i add a choice to a poll that didn't have any choices from the admin site, this won't be reflected on the site until i restart the server or i change some code in the project, even though i'm passing a callable object as argument to the filter (which is the same as the previous filter in that same line), i searched in the rest of documentation and i also looked at the definitive guide to django but i found nothing, that could help me, so i don't really know if there's something wrong with the code, or i'm lacking some understanding of django or a particular concept of python itself
Your current query is incorrect because, You are filtering poll ids, if choice objects of the same ids are present in the database, which is not accurate.
To filter out polls with no choice, you need to do
queryset=Poll.objects.filter(choice__isnull=False).order_by('-pub_date').distinct()[:5] #Get only polls with a choice.
Now,every Poll before now can be filtered like this:
queryset = Poll.objects.filter(choice__isnull=False, pub_date__lte=timezone.now()).order_by('-pub_date').distinct()[:5]

Issue with lazy translation and Basic Blog in Django

I've been using the blog that comes with the Django Basic Apps for quite some time now, and haven't had any problems until now. The error I have been getting happens any time I try to access the single page for a newly created blog post. Note that this is only happening for recently created posts; earlier posts work just fine.
This is the only thing Django tells me:
No <django.utils.functional.__proxy__ object at 0x105ab8890> found for
I've done a bit more research and determined that Django has some sort of a lazy translation functionality, and that is the object that is not being found. I'm still completely confused as to what parameter I could have changed that would suddenly cause this issue.
Have you added some _() translated strings recently? Could you post the code, or an example of which creates this error?

Categories

Resources