Django database sqlite display of value of attribute - python

I'm on a project using django and I wrote my models.py
I have two classes
class Adresse(models.Model):
numV=models.IntegerField(blank=False,null=False)
complementdest=models.TextField(blank=False,null=False)
complementadr=models.TextField(blank=False,null=False)
commune=models.TextField(blank=False,null=False)
codeP=models.IntegerField(blank=False,null=False)
pays=models.TextField(blank=False,null=False)
def __str__(self):
return self.numV
return self.complementdest
return self.complementadr
return self.commune
return self.codeP
return self.pays
def __Adr__(self):
return self.adr1.all()
and
class CompteCandidat(myUser):
sexe = models.TextField(max_length=10)
datecr = models.DateTimeField(auto_now_add = True)
adresse=models.OneToOneField('Adresse',related_name='adr1',null=True, default=None)
def __str__(self):
return self.first_name
return self.last_name
return self.email
return self.sexe
def __Adr__(self):
return self.adresse.all()
I try to do some tests like this:
adresse=Adresse(numV='254',complementdest='xxxxx',complementadr='Eugene napoleon',commune='Paris',codeP='75012',pays='France')
c1=CompteCandidat(username='Luna',first_name='celia',last_name='durand',password='CCC',email='hello2#gmail.com',type='candidat',adresse=adresse)
adresse.save()
c1.save()
and when I try to see what I have in my Adresse or in my CompteCandidat by using this command it didn't work
>>> Adresse.__getattribute__(numV)
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'numV' is not defined
i want to know what i'm suppose to do to display what I have in Adresse and CompteCandidat in order to be sure that the add works
i know i Can do :
>>> adresse.numV
'254'
but it works only in the console there is an another way to consult all the database without using the name of the temporery variables ????

You can use
Adresse.objects.all()
to see all records or Adresse.object.filter(numV='254)
to see records satisfying this condition.
For full reference please check:
https://docs.djangoproject.com/ja/1.9/topics/db/queries/

At first in the console try this:
>>>A = {numV='254',complementdest='xxxxx',complementadr='Eugene napoleon',commune='Paris',codeP='75012',pays='France'}
>>> adresse = Adresse(**A)
>>> adresse.save()
At first you will face an error beacuse your numV is Integer but you are assigning an String to it, so should edit numV = '254' to numV = 254 at first line.
Then try above steps again and post that in which step face error.

Two things :
__str__ must only return a single string - as it stands your code tries to return multiple non string values.
the __getattribute__ method (and it's counterpart getattr) should be passed the name of the attribute i.e. a string. Also you shouldn't be trying to call __getattribute__ directly except in exceptional circumstances: ie. you have some form of circular access confilct - which you don't here.
There is no reason that adresse.numV shouldn't work directly in your code - that is the normal way to retrieve attributes from an instance. You should only use getattr if you have the attribute name in a string from elsewhere.
At the risk of sounding rude - if you are struggling to write code that correctly accesses attributes then maybe trying to write a Django App is a case of trying to run before you walk.

Related

How to solve django with mysql error in inserting

I create models for MySQL the foreign key
constraints always returning error
The model is
class AirPort(models.Model):
code = models.CharField(max_length=3)
city = models.CharField(max_length=100)
def __str__(self):
return f"{self.id} - CODE =>{self.code} :: CITY=> {self.city}"
class Flight(models.Model):
orgin_id = models.ForeignKey(AirPort,on_delete=models.CASCADE,related_name="dep")
dest_id = models.ForeignKey(AirPort,on_delete=models.CASCADE,related_name="arrival")
duration = models.IntegerField()
def __str__(self):
return f"{self.id} - {self.orgin} TO {self.dest} will take {self.duration} minutes"
and the shell output is
a=Flight(orgin_id=1,dest_id=2,duration=120)
Traceback (most recent call last):
File "", line 1, in
File "/home/kid/PycharmProjects/hardward/venv/lib/python3.6/site-packages/django/db/models/base.py", line 467, in init
_setattr(self, field.name, rel_obj)
File "/home/kid/PycharmProjects/hardward/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 210, in set
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "1": "Flight.orgin_id" must be a "AirPort" instance.
Try
a=Flight(orgin=AirPort.object.get(id=1),dest=AirPort.object.get(id=2),duration=120)
You may try this
flight_result=Flight()
flight_result.orgin_id = AirPort.object.first()
flight_result.dest_id = AirPort.object.last()
flight_result.duration = 1000
flight_result.save()
Have you run python manage.py makemigrations...and migrated the data with python manage.py migrate
I received this error because I did not see the comma at the end
order.employee=Employee.objects.get(employee_id=x),
Its origin was that I used Order.objects.create() before, for which one uses comma separated attribute assignments and I did not immediately delete the commas. May it help someone who also sat too long in front of the computer :)

Receiving True boolean value for Django unit tests instead of False

I'm doing some unit tests for my Django database and I keep getting a True value instead of the False I expected to get because that entry isn't in my database:
import requests
from django.test import TestCase
from convoapp.models import InputInfo
class InputInfoTestCase(TestCase):
def setUp(self):
#valid entry
InputInfo.objects.create(name="Skywalker", conversation_id='1', message_body='I am a Jedi, like my father before me')
#invalid entry - missing 'name' field
InputInfo.objects.create(conversation_id='4', message_body="No, I am your Father")
#invalid entry - integer entered instead of string
InputInfo.objects.create(name='Leia', conversation_id=3, message_body='You are a little short')
def test_for_valid_entries(self):
luke = InputInfo.objects.get(name='Skywalker')
self.assertTrue(bool(luke), True)
def test_for_invalid_entries(self):
vader = InputInfo.objects.get(conversation_id='4')
#invalid because of non-strong entry for conversation_id
#leia = InputInfo.objects.get(name='Leia')
self.assertFalse(bool(vader))
I get the error:
Traceback (most recent call last):
File "C:\Users\ELITEBOOK\documents\github\challenge\convoapp\tests.py", line 25, in test_for_invalid_entries
self.assertFalse(bool(vader))
AssertionError: True is not false
Why is vaderreturning True? I assume it's because of InputInfo.objects.create(conversation_id='4', message_body="No, I am your Father"), is it because the entry is temporarily created? Because after the test ends it's not in my database
the setUp functions is called before each test so yeah you have the vader entry in your db (because you request conversation_id=4 which exists since setUp was called before testing).
That said, casting to bool doesn't make a lot of sense, if your trying to see if you have the entry or not you should user :
self.assertIsNone(vader)
or
self.assertTrue(vader is None)
This way you know exactly what you are testing
you are creating an object with the id 4 thus its returning true, and as its test database thus you cannot find data after the test ends
rather if you think its mistaking
try the lower code and check
def test_for_invalid_entries(self):
vader = InputInfo.objects.get(conversation_id=5)
#invalid because of non-strong entry for conversation_id
#leia = InputInfo.objects.get(name='Leia')
self.assertFalse(bool(vader))

Accessing variable outside class using inheritance

I am trying to inherit a variable from base class but the interpreter throws an error.
Here is my code:
class LibAccess(object):
def __init__(self,url):
self.url = url
def url_lib(self):
self.urllib_data = urllib.request.urlopen(self.url).read()
return self.urllib_data
class Spidering(LibAccess):
def category1(self):
print (self.urllib_data)
scrap = Spidering("http://jabong.com")
scrap.category1()
This is the output:
Traceback (most recent call last):
File "variable_concat.py", line 16, in <module>
scrap.category1()
File "variable_concat.py", line 12, in category1
print (self.urllib_data)
AttributeError: 'Spidering' object has no attribute 'urllib_data'
What is the problem with the code?
You will need to define self.urllib_data prior to accessing it. The simples way would be to create it during initialization, e.g.
class LibAccess(object):
def __init__(self,url):
self.url = url
self.urllib_data = None
That way you can make sure it exists everytime you try to access it. From your code I take it that you do not want to obtain the actual data during initialization. Alternatively, you could call self.url_lib() from __init__(..) to read the data for the first time. Updating it later on would be done in the same way as before.

Generating instances of class in loop gives TypeError: 'list' object is not callable

I've looked through a lot of replies regarding this error, however none was helpfull for my special case and since I'm new to Python, I have difficulties applying the hints to my problem.
I have a class in a file Aheat.py that reads
class Aheat():
name = ""
time = 0
place = 0
def __init__(self,name,time,place):
self.name = name
self.time = time
self.place = place
And a file main.py where I want to read a html file, extract information, and create a list of objects of my class to work with them later on.
The (hopefully) essential part of my main.py reads
import urllib2
import re
from Aheat import Aheat
s = read something from url
ssplit = re.split('<p', s) # now every entry of ssplit contains an event
# and description and all the runners
HeatList = []
for part in ssplit:
newHeat = Aheat("foo",1,1) # of course this is just an example
HeatList.append(newHeat)
But this gives me the following error:
Traceback (most recent call last):
File "/home/username/Workspace/ECLIPSE/running/main.py", line 22, in <module>
newHeat = Aheat("foo",1,1)
TypeError: 'list' object is not callable
which is thrown when performing the second iteration.
If I take out the generation of the object of the loop, i.e.
newHeat = Aheat("foo",1,1)
for part in ssplit:
HeatList.append(newHeat)
My code executes without a problem, but this is not what I want. I'm also not sure, if I can initialize a specific number of instances a priori, since the number of objects is estimated in the loop.
I'm using Eclipse and Python 2.7.
regex is going to bite you.
<p == <pre> || <progress> || <param> || <p> || (any user created directives on a page.)
follow the links in your comments to read up on why we shouldn't parse html with regex.
Thanks, #MarkR ( btw, I was only supplementing your comment and I was agreeing with you )
Why not put the list in your class or better yet extend list functionality with your class.
class AHeat(list):
def append(self,name,time,place):
return super(AHeat,self).append([name,time,place])
# main
heatList= AHeat()
heatList.append("foo",1,2)
heatList.append("bar",3,4)
print(heatList[0])
print(heatList[1])
> ['foo', 1, 2]
> ['bar', 3, 4]
Also

AppEngine -> "AttributeError: 'unicode' object has no attribute 'has_key'" when using blobstore

There have been a number of other questions on AttributeErrors here, but I've read through them and am still not sure what's causing the type mismatch in my specific case.
Thanks in advance for any thoughts on this.
My model:
class Object(db.Model):
notes = db.StringProperty(multiline=False)
other_item = db.ReferenceProperty(Other)
time = db.DateTimeProperty(auto_now_add=True)
new_files = blobstore.BlobReferenceProperty(required=True)
email = db.EmailProperty()
is_purple = db.BooleanProperty()
My BlobstoreUploadHandler:
class FormUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
try:
note = self.request.get('notes')
email_addr = self.request.get('email')
o = self.request.get('other')
upload_file = self.get_uploads()[0]
# Save the object record
new_object = Object(notes=note,
other=o,
email=email_addr,
is_purple=False,
new_files=upload_file.key())
db.put(new_object)
# Redirect to let user know everything's peachy.
self.redirect('/upload_success.html')
except:
self.redirect('/upload_failure.html')
And every time I submit the form that uploads the file, it throws the following exception:
ERROR 2010-10-30 21:31:01,045 __init__.py:391] 'unicode' object has no attribute 'has_key'
Traceback (most recent call last):
File "/home/user/Public/dir/google_appengine/google/appengine/ext/webapp/__init__.py", line 513, in __call__
handler.post(*groups)
File "/home/user/Public/dir/myapp/myapp.py", line 187, in post
new_files=upload_file.key())
File "/home/user/Public/dir/google_appengine/google/appengine/ext/db/__init__.py", line 813, in __init__
prop.__set__(self, value)
File "/home/user/Public/dir/google_appengine/google/appengine/ext/db/__init__.py", line 3216, in __set__
value = self.validate(value)
File "/home/user/Public/dir/google_appengine/google/appengine/ext/db/__init__.py", line 3246, in validate
if value is not None and not value.has_key():
AttributeError: 'unicode' object has no attribute 'has_key'
What perplexes me most is that this code is nearly straight out of the documentation, and jives with other examples of blob upload handler's I've found online in tutorials as well.
I've run --clear-datastore to ensure that any changes I've made to the DB schema aren't causing problems, and have tried casting upload_file as all sorts of things to see if it would appease Python - any ideas on what I've screwed up?
Edit: I've found a workaround, but it's suboptimal.
Altering the UploadHandler to this instead resolves the issue:
...
# Save the object record
new_object = Object()
new_object.notes = note
new_object.other = o
new_object.email = email.addr
new_object.is_purple = False
new_object.new_files = upload_file.key()
db.put(new_object)
...
I made this switch after noticing that commenting out the files line threw the same issues for the other line, and so on. This isn't an optimal solution, though, as I can't enforce validation this way (in the model, if I set anything as required, I can't declare an empty entity like above without throwing an exception).
Any thoughts on why I can't declare the entity and populate it at the same time?
You're passing in o as the value of other_item (in your sample code, you call it other, but I presume that's a typo). o is a string fetched from the request, though, and the model definition specifies that it's a ReferenceProperty, so it should either be an instance of the Other class, or a db.Key object.
If o is supposed to be a stringified key, pass in db.Key(o) instead, to deserialize it.
Object is a really terrible name for a datastore class (or any class, really), by the way - the Python base object is called object, and that's only one capitalized letter away - very easy to mistake.
has_key error is due to the ReferenceProperty other_items. You are most likely passing in '' for other_items when appengine's api expects a dict. In order to get around this, you need to convert other_items to hash.
[caveat lector: I know zilch about "google_app_engine"]
The message indicates that it is expecting a dict (the only known object that has a has_key attribute) or a work-alike object, not the unicode object that you supplied. Perhaps you should be passing upload_file, not upload_file.key() ...

Categories