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?
Related
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.
I was following Django tutorial, and got stuck where it asked me to replace the default template for administrative part of the site with my own. The problem was a typo in the template's name. I suspected there must be a problem like that, but to troubleshoot the problem it'd be very helpful to see some kind of report from Django on what template it used to render a particular page. Is there any way to do this?
First if you have set DEBUG = True django automatically gives you information about where django was looking for templates (in general and especially in case it didn't find one)
You should see something like this:
second you can add the popular django plugin django-debug-toolbar. It can show you for each request what templates were used and what their context was.
see: https://django-debug-toolbar.readthedocs.io/en/stable/panels.html#template
Still, not exactly the answer, but something to get me closer. One could start Django shell, and then try this:
>>> from django.template.loader import get_template
>>> get_template('template/name').origin.name
to find out what template was actually used. This is still not enough to see though which templates were considered while resolving the template.
I'm new to both Django and Python so please forgive me if I come off as annoying....I'm just very much misinformed!
Error Code: http://i.gyazo.com/68d88cabf536b129dc37cde6c3ae319c.png
I've googled about this 'KeyError' and it seems to be related to clean(). However, the example my lecturer gave me worked ok without it but when I tried to recreate what he gave me I kept getting this error.
A bit of info: I had originally had a ForeignKey for the user for each submission so I changed it to a simple form to fill in (not a permanent solution) but I still get a KeyError.
Here is my models, views and forms:
http://pastebin.com/rAX5PDHQ
Sorry if I left something out. I'll respond ASAP if you all need more info.
Again, sorry if this is a silly question. But I'm utterly lost to be honest.
Thank you!
PS Sorry I really tried the code formatting but I kept getting an error saying it was incorrect thought the preview said it was ok. And I can't post more than one link.
You don't have a field named user in your form. Try changing the relevant line to:
bd = BloodData (respondent=cd['respondent'],
in your "storeBloodData" view.
The problem seems to be in your view storeBloodData,at this point.
bd = BloodData (respondent=cd['user'],
The form has no field named 'user'.You may replace it with a relevant field present declared in the form.
Also, it is better to use DICT.get(key)when you are not sure if the dict contains that particular key or not. This way you'll simply be returned None when the key is absent and you'll be able to dodge KeyError.
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!
I have recently started experimenting with Django for some web applications in my spare time. While designing the data model for one, I came across the dilemma of using inheritance to define a user of the website or using a technique known as monkey patching with the User class already supplied by the framework.
I tried to add a field by means of (after having defined all my models etc. without errors, according to python manage.py validate):
User.add_to_class('location', models.CharField(max_length=250,blank=True))
and executed the syncdb command. However, I keep getting this error
OperationalError: no such column:
auth_user.location
whether I am in the admin view of the site or the manage.py shell. There must be an extra step I'm missing, but there seems to be limited documentation on the whole monkey patching technique. So I'm asking you for assistance before I resort to inheritance. Any code, tips, or pointers to additional documentation are of course welcome.
Thanks in advance.
PS. I'm aware this technique is ugly, and probably ill-advised. ;)
There's an alternative to both approaches, which is to simply use a related profile model. This also happens to be a well-documented, highly recommended approach. Perhaps the reason that the add_to_class approach is not well-documented, as you noted, is because it's explicitly discouraged (for good reason).
When you add a field to any model, even if you do it the 'official' way, you need to migrate the database - Django doesn't do it for you. Drop the table and run ./manage.py syncdb again.
You might want to investigate one of the migrations frameworks, such as south, which will manage this sort of thing for you.
Here's a (slightly older) way of extending the User model.
Here's what the docs have to say.
And here's a recent conversation on django-users about the topic.
Djangos framework uses metaclasses to initialize the tables. That means you can't monkey-patch in new columns, unless you also re-initialize the class, which I'm not sure is even possible. (It may be).
See Difference between returning modified class and using type() for some more info.
I guess you might run into problems regarding where is your monkeypatch defined. I guess django syncdb creates databse tables only from the "pure" auth application, so your model will then be without "location", and then your site with the patch will look for the field.
Probably less painful way of adding additional info to user profiles is described in Django docs.