Appending to relationship - python

Given a simple one to many relationship where one page can be linked to multiple errors:
class Page(Base):
...
errors = relationship('Error', back_populates='page')
class Error(Base):
...
page = relationship('Page', back_populates='errors')
I add error objects to a page object simple by
page.errors.append(error)
This works. However PyCharm warns about Error would have no reference "append".
My Question: Is this just PyCharm not understanding that Page.errors is of type list(?) and not Error or is is there something I should do better?

If someone stumbles upon the same problem: I did not notify any problems yet and so I guess it is simply pycharm not recognising the type correctly. You can simple help it by using type hints:
class Page(Base):
...
errors: list = relationship('Error', back_populates='page')

Related

How can I override __str__ in models.py?

Apologies if this is a silly question, I am pretty new to python and django.
I am following along with a django tutorial, and we are creating a fake movie site that lists movies by genre, title, etc.
I am currently trying to override the __str__ function in the models.py file, so rather than displaying Genre (1), it displays the actual genre (ex. "Action").
Here's how my models.py looks currently:
from tkinter import CASCADE
from django.db import models
from django.utils import timezone
# Create your models here.
class Genre(models.Model):
name = models.CharField(max_length=255)
def __str__ (self):
return self.name
class Movie(models.Model):
title = models.CharField(max_length=255)
release_year = models.IntegerField()
number_in_stock = models.IntegerField()
daily_rate = models.FloatField()
genre = models.ForeignKey(Genre, on_delete=models.CASCADE)
date_created = models.DateTimeField(default=timezone.now)
However, vscode is underlining the
def __str__ (self):
When I hover over it, it tells me:
str does not return str pylint(E0307: invalid -str- returned
I tried looking at other solutions, but I could not find one that seemed to match my scenario, so I do apologize if this has been solved elsewhere, and I am too incompetent to understand the problem.
Thanks for your patience!
This question has a couple of good illustrations of why it's important to understand your code before you rely too heavily on IDEs and tools like pylint. I've two suggestions:
The pylint error is just a warning to indicate that your code might have a problem - it is not an absolute fact. The E0307 error says:
Used when a __str__ method returns something which is not a string.
It would be more accurate if it had said "when the pylint checker cannot be sure that you're returning a string". In this case, it's because it doesn't recognise that a Django CharField will in fact return a valid string instance. Your existing __str__ method would work perfectly fine if you ran the code - regardless of what pylint thinks.
You can work around this by forcing the return value to look like a string, e.g., with:
return str(self.name)
or
return f"{self.name}"
But it would be equally valid to disable the check for this line in pylint, with the understanding of why it reported the error. Just applying a fix found on Stack Overflow without understanding the issue is going to make it hard to debug your code in future.
There is a second, completely unrelated issue in your code which will cause you problems later, and that is this line:
from tkinter import CASCADE
I am pretty confident that this has been inserted by your IDE, without your explicitly adding it, because you tried to use CASCADE in your ForeignKey. This is the IDE trying to be helpful - unfortunately it has imported something completely useless, that can cause you problems when you try to deploy your code.
Both of these highlight an important principle: don't rely on IDEs or linters. They are not a substitute for understanding your own code.

HStore.DictionaryField returns a string when this part of the code exist in Django. Not sure why

Will try to explain this as best I can. The snippet of code see below screenshot (narrowed it down to line 358) causes models with HStore.DictionaryField on, another section of the project, to return a string instead of the HStore Dict object.
Removing this section resolves the issue fixes the issue and returns the HStore Dict.
Cannot figure out how this snippet of code can affect that.
This is in a admin.py
class SomeModel(models.Model):
allowed_vals = hstore.DictionaryField()

Unresolved reference in Django's docstring in PyCharm

I use Google Style Python Docstrings like in this Example for my Django's project.
When i create a class and using an attributes notation in docstring, Pycharm always say - "Unresolved reference".
class Post(models.Model):
"""
Class for posts.
Attributes:
title(str): Post title.
"""
title = models.CharField(max_length=120)
I understand that PyCharm doesn't see self for title and def __init__() function and write this error, but in Django I've never seen using def __init__() for classes inherited from models.
What should I do? Is this my error or does PyCharm not see context in this case? Should I use def __init__() or something else or write docsting in another way?
PyCharm does not appear to have support for this currently. The active issue for this in JetBrains issue tracker is https://youtrack.jetbrains.com/issue/PY-16760, please consider upvoting it to get it fixed. The only workaround if you want to avoid seeing these "Unresolved reference" errors in your docstrings is to disable the inspection in Preferences > Editor > Inspections > Unresolved references.
Another option that I have tried in the past is removing the "Attributes:" header and writing my attribute documentation on the same indentation level as the rest of the docstring. This no longer gives you a warning, but you are no longer conforming 100% to the Google Docstring Style Guide.
I solved this issue by adding a '# noqa' after the 'Attributes:', because i did not want to disable the unresolved reference warning.
So this would be the final docstring:
"""
Class for posts.
Attributes: # noqa
title(str): Post title.
"""
The following works for me: In your docstrings, writing Attribute: instead of Attributes: makes the error disappear. That allows you to keep the indentation level

python cherrypy session usage example of cherrypy.lib.sessions

I am total newbie with cherrypy.
My setup: Arch Linux, Python 3.3, tornado, cherrypy 3.2
Trying to implement session handling for a web app using cherrypy.lib.sessions (for some reason often referred to as cherrypy.sessions in various forums, might be another version)
I am looking for an example of the following:
instantiate a session object
set a value of an arbitrarily named attribute
write session into a session file
read session info from session file
access the the value of the modified attribute
My (relevant) code:
import cherrypy
class RequestHandlerSubmittedRequest(tornado.web.RequestHandler):
def get(self):
SetState(self)
def SetState(self):
cherrypy.config.update({'tools.sessions.on': True})
cherrypy.config.update({'tools.sessions.storage_type': 'file'})
#directory does exist
cherrypy.config.update({'tools.sessions.storage_path': '/tmp/cherrypy_sessions'})
cherrypy.config.update({'tools.sessions.timeout': 60})
cherrypy.config.update({'tools.sessions.name': 'hhh'})
So far so good. Now:
obj_session = cherrypy.lib.sessions.FileSession
Here I get the first snag (or misunderstanding).
The returned obj_session contains no session ID of any kind, just an empty object frame. Also: no file is created at this point in /tmp/cherrypy_sessions -
should not it be there now? I would expect it to be created and named after its session ID.
OK, no ID in the object, let's assign one:
session_id = obj_session.generate_id(self)
This returns a long random string as it should I guess
And now I don't know how to proceed with assignments and saving calling obj_session.save() or obj_session.load() with several variations of input gives "AttributeError: 'module' object has no attribute X" where X can be "load" and couple of other keywords. Passing self or obj_session itself to the methods does not help, just changes the wording of the error. I must be going in a very wrong direction in general.
So, is there an example of those five steps above? I could not find one anywhere.
Thanks.
Igor

Exception when using filter to retrieve a django model

To retrieve a django object, I am using the filter function as follows:
product = Product.objects.filter(code=request.POST['code'])
Then, when I try to access the retrieved object as:
product[0].description
I get an exception "list index out of range". Although, the filter is indeed returning an object because the len(product) call is showing "1".
However, if I hardcode the code value (retreived from the post above), I get no exception.
All I want to do is get access to the product object based on the code.
Using Product.objects.get does not work either...
Any help will be appreciated.
Thanks in advance.
You should probably validate that request.POST['code'] is valid before you try to use it in anything:
# code will be None if it isn't found in request.POST
code = request.POST.get('code')
if code:
products = Product.objects.filter(code=code)
for product in products:
print product.description
Hope this helps a bit.
It's not an answer but in this type of case, where the results make no sense, it's normally time to get the debugger out (either pdb or preferably ipdb).
import ipdb;ipdb.set_trace()
Then look at product. What actually is it? Look at request.POST['code'] and see what is different from just passing a literal. Also would be interested to know what the attempt to use 'get' actually does. You say it doesn't work but what does it actually do?

Categories