update foreignkey items from django shell - python

Following is the models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User)
belongs_to_user_category = models.ForeignKey(UserCustomCategory, null=True, blank=True)
class UserHistory(models.Model):
date_time = models.DateTimeField()
user = models.ForeignKey(UserProfile, null=True, blank=True)
points_earned = models.DecimalField(max_digits=5, decimal_places=3)
as is clear, userhistory is a foreign key to UserProfile. For the test purpose i wanted to update the points of the user whose name starts with a
I wrote the following code in the python shell:
from myapp.models import *
uobj = UserProfile.objects.all()
for i in uobj:
if i.user.username[0] == 'a':
b = UserHistory.objects.create(user=i)
b.points_earned = random.random(10, 100)
b.date_time = datetime.datetime.now()
b.save()
i have also tried b = UserHistory.objects.get_or_create(user=i) with same error
and i get the following error:
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (160, 0))
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (13, 0))
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (63, 0))
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/IPython/ultraTB.py", line 667, in text
locals,formatvalue=var_repr))
File "/usr/lib/python2.6/inspect.py", line 875, in formatargvalues
specs.append(strseq(args[i], convert, join))
File "/usr/lib/python2.6/inspect.py", line 830, in strseq
return convert(object)
File "/usr/lib/python2.6/inspect.py", line 872, in convert
return formatarg(name) + formatvalue(locals[name])
KeyError: 'connection'
IPython's exception reporting continues...
---------------------------------------------------------------------------
IntegrityError Traceback (most recent call last)
IntegrityError: (1048, "Column 'date_time' cannot be null")

When you use the create method of the default model manager in Django, it will also attempt to create that instance into the database and save it. You can do this in two ways, but I'll show you what you can do with your approach, which may help in some understanding.
First, you will want to create a UserHistory object, but don't actually save it. This is done by simply instantiating that model class with any default values you'd like:
b = UserHistory(user=i)
After that, you can set the other attributes.
b.points_earned = random.randint(10, 100)
b.date_time = datetime.datetime.now()
b.save()
And this will work. Because you're now saving b after you've set the date_time.
There are ways to improve this of course, you can simply create everything in one call since you're doing it in one logical step, like so:
b = UserHistory.objects.create(
user=i,
points_earned=random.randint(10, 100),
date_time=datetime.datetime.now(),
)
You can further improve this by reading the DateField docs for Django, which will give you some tips on how to set the default date to the current time.
Hope this helps!

Related

Python: How can I execute custom functionality in a custom Exception

I have a script that takes note of tables that do not contain primary keys. At the end of the execution of this script I want to raise an error that prints sequentially prints the names of these tables.
class MissingPrimaryKeysError(Exception):
"""MissingPrimaryKeysError exception class"""
def __init__(self, missing_keys, message="Some primary keys are missing"):
self.missing_keys = missing_keys
self.message = message
print('The following tables are missing primary keys')
for pk in missing_keys:
print(pk)
tables_missing_pk = ['some_table', 'other_table']
if tables_missing_pk:
raise MissingPrimaryKeysError(tables_missing_pk)
I tried to overwrite the __init__ method of the base class Exception (shown above), but this does not result in my envisioned result. The envisioned result is as follows:
Traceback (most recent call last):
File "<filepath>", line 13, in <module>
raise MissingPrimaryKeysError(tables_missing_pk)
__main__.MissingPrimaryKeysError: The following tables are missing primary keys:
some_table
other_table
What is happening now is the following:
The following tables are missing primary keys
some_table
other_table
Traceback (most recent call last):
File "d:/git/DataLake.General.DataStore.Notebooks/notebooks/raw/ods/pks_test.py", line 13, in <module>
raise MissingPrimaryKeysError(tables_missing_pk)
__main__.MissingPrimaryKeysError: ['some_table', 'other_table']
It appears as if the logic in my custom __init__ function is indeed executed, and then the Exception is raised "normally" and just flat out printing the list. How can I get to the envisioned result?
Provide a __repr__ implementation that defines how you want your exception to be rendered when it's printed as part of a stack trace (or elsewhere):
class MissingPrimaryKeysError(Exception):
"""MissingPrimaryKeysError exception class"""
def __init__(self, missing_keys, message="Some primary keys are missing"):
self.missing_keys = missing_keys
self.message = message
def __repr__(self):
return (
self.message + ':\n'
+ '\n'.join(str(pk) for pk in self.missing_keys)
)

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 :)

Get the list of due assignments using Google Classroom API

I am trying to get the list of assignments due/coursework for all the courses using the Google Classroom API. I am getting a list of courses using the below code :
results = service.courses().list(pageSize = 10).execute()
courses = results.get('courses',[])
Once I get the list of all the courses, I loop over each the course and try to supply the courseID in order to get the list of coursework using courses.courseWork.list method, but I'm getting an error.
I have written the following code :
for course in courses :
print(course['name'])
print "Assignments you have due in this course : "
print course[u'id']
course_work_results = service.courses().courseWork().list().execute()
print course_work_results
Since I am not supplying the courseID anywhere (which I need to know how to do), I get the following error :
Traceback (most recent call last):
File "classroom.py", line 53, in <module>
course_work_results = service.courses().courseWork().list().execute()
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 727, in method
raise TypeError('Missing required parameter "%s"' % name)
TypeError: Missing required parameter "courseId"
The error is caused due to the line
course_work_results = service.courses().courseWork().list().execute()
How to fix this ?

How can I get the traceback object ( sys.exc_info()[2] , same as sys.exc_traceback ) as a string?

I have a function which catches all exceptions, and I want to be able to get the traceback as a string within this function.
So far this is not working:
def handle_errors(error_type, error_message, error_traceback):
"""catch errors"""
import traceback
error = {}
error['type'] = error_type.__name__
error['message'] = str(error_message)
error['file'] = os.path.split(error_traceback.tb_frame.f_code.co_filename)[1]
error['line'] = error_traceback.tb_lineno
error['traceback'] = repr(traceback.print_tb(error_traceback))
### finalise error handling and exit ###
sys.excepthook = handle_errors
It's the error['traceback'] line which is wrong. Do i even need to use the traceback module?
As per this other vaguely similar question, I have tried:
error['traceback'] = repr(error_traceback.print_exc())
...but this gives an error:
Error in sys.excepthook:
Traceback (most recent call last):
File "xxxxxxxxxxx", line 54, in handle_errors
error['traceback'] = repr(error_traceback.print_exc())
AttributeError: 'traceback' object has no attribute 'print_exc'
Use traceback.format_tb() instead of print_tb() to get the formatted stack trace (as a list of lines):
error['traceback'] = ''.join(traceback.format_tb(error_traceback))
print_tb() directly prints the traceback, that's why you get None as a result (that's the default for any Python function that doesn't return anything explicitely).
traceback.format_exc([limit])
This is like print_exc(limit) but
returns a string instead of printing to a file.
New in version 2.4.
error['traceback'] = traceback.format_exc(error_traceback)

AssertRaises fails even though exception is raised

I am running into the following rather strange problem:
I am developing a django app and in my models class I am defining an exception that should be raised when a validation fails:
class MissingValueException(Exception):
"""Raise when a required attribute is missing."""
def __init__(self, message):
super(MissingValueException, self).__init__()
self.message = message
def __str__(self):
return repr(self.message)
This code is called from a publication class in a validation method:
def validate_required_fields(self):
# Here is the validation code.
if all_fields_present:
return True
else:
raise MissingValueException(errors)
In my unit test I create a case where the exception should be raised:
def test_raise_exception_incomplete_publication(self):
publication = Publication(publication_type="book")
self.assertRaises(MissingValueException, publication.validate_required_fields)
This produces the following output:
======================================================================
ERROR: test_raise_exception_incomplete_publication (core_knowledge_platform.core_web_service.tests.logic_tests.BusinessLogicTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/tests/logic_tests.py", line 45, in test_raise_exception_incomplete_publication
self.assertRaises(MissingValueException, method, )
File "/usr/lib/python2.7/unittest/case.py", line 465, in assertRaises
callableObj(*args, **kwargs)
File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/models.py", line 150, in validate_required_fields
raise MissingValueException(errors)
MissingValueException: 'Publication of type book is missing field publisherPublication of type book is missing field titlePublication of type book is missing field year'
So it looks like the exception is raised (which is the case - I even checked it in an interactive IPython session), but it seems that assertRaises is not catching it.
Anyone has any idea why this might happen?
Thanks
This could happen if your tests and your product code are importing your exception class through two different paths, so asserRaises doesn't realize that the exception you got was the one you were looking for.
Look at your imports, make sure that they are the same in both places. Having the same directories available in two different ways in your PYTHONPATH can make this happen. Symbolic links in those entries can also confuse things.

Categories