django states attibuteError although attribute is assigned - python

I have a Payment Django model that has a CheckNumber attribute that I seem to be facing issues with, at least whilst mentioning the attribute in the str method. It works just fine on the admin page when creating a Payment instance, but as soon as I called it in the method it gave me the following error message:
Request URL: http://127.0.0.1:8000/admin/Vendor/payment/
Django Version: 3.0.7
Exception Type: AttributeError
Exception Value:
'Payment' object has no attribute 'CheckNumber'
Exception Location: /Users/beepboop/PycharmProjects/novatory/Vendor/models.py in __str__, line 72
Python Executable: /Users/beepboop/Environments/novatory/bin/python3.7
Python Version: 3.7.2
this is my code:
class Payment(models.Model):
Vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
Amount = models.DecimalField(decimal_places=2, blank=True, max_digits=8)
PaymentDate = models.DateField(name="Payment date", help_text="Day of payment")
CheckNumber = models.IntegerField(name="Check number", help_text="If payment wasn't made with check, leave blank", blank=True)
def __str__(self):
return f"Vendor: {self.Vendor.Name} | Amount: {prettyPrintCurrency(self.Amount)} | Checknumber: {self.CheckNumber}"
I would absolutely love any comments/suggestions about the cause of the error

In my opinion, you have introduced CheckNumber field in the Payment models recently with no migration. make sure you run the migration then you can do that using the following command.
python manage.py migrate
This will create a new field in the Payment table. Hopefully, this will resolve your issue.
please clean the database and then run the migration command.
To clean the database you need to write the following command(Don't run this command in production):
python manage.py flush
After the cleaning, you can make an initial migration using the following command:
python manage.py makemigrations
and then migrate those changes to the database table:
python manage.py migrate

So it turns out that when you pass a name value in a model field, it changes the name of the field with it, I personally thought that it would change the name when displayed in the Django admin. My fix was to just remove the name value and migrate, that fixed it for me.

Related

Python/Django 'OperationalError' in admin Django Rest Framework (DRF)

I keep getting the Operational error below in my Django admin when I try to update a models table.
I'm trying to add a new field to the polls table.
What could be the problem?
Thanks in advance!
OperationalError at /admin/vote/poll/add/
no such table: main.auth_user__old
Request Method: POST
Request URL: http://localhost:8000/admin/vote/poll/add/
Django Version: 2.0.3
Exception Type: OperationalError
Exception Value: no such table: main.auth_user__old
Exception Location: D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303
Python Executable: D:\Studio\Python\REST\elections\env\Scripts\python.exe
Python Version: 3.9.0
Python Path:
The polls model: models.py
class Poll(models.Model):
question = models.CharField(max_length=100)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
pub_date = models.DateTimeField(auto_now=True)
The urls.py code:
urlpatterns = [
path("polls/", PollList.as_view(), name="polls_list"),
path("polls/<int:pk>/", PollDetail.as_view(), name="polls_detail"),
]
Is there any specific reason you are using Django v2 instead of v3.
You could do a couple of things to resolve this:
Upgrade Django version to 2.2 or above.
Downgrade SQLite version if you are using one.
After that you can delete the old database, and run you migrations again:
python manage.py makemigrations
python manage.py migrate

Django - How to fix model with id field

I unintentionally created a model with a field "id" and did the migration. The model at first looked like this:
class VsSession(models.Model):
id = models.TextField(default="123"),
state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10)
Afterwards I rename the field to vs_session:
class VsSession(models.Model):
vs_session = models.TextField(default="123"),
state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10)
Now whenever I try to use the model e.g., like this:
def get(self, request):
try:
sessionid = uuid.uuid4()
new_session = VsSession(vs_session=sessionid, state="active")
new_session.save()
return Response({'success': 'true', 'vssession': sessionid})
except Exception as e:
print(str(e))
return Response({'success': 'false'})
I get this error:
VsSession() got an unexpected keyword argument 'vs_session'
Can anybody please tell me what I did wrong and how to fix this.
Thank you very much!
So I have no idea why this is working now, but I fixed it. What I did is
Removed vs_session variable from the model
Added created_at = models.DateTimeField(auto_now_add=True) to the model
makemigration and migrate
Run code/stop code
Add vs_session variable to model
makemigration an migrate
Everything is fine :)
Did you try running python manage.py makemigrations? After running this you should see a message telling you the field was renamed. To actually apply the migration to your database you can run python manage.py migrate

Even when value set: TypeError at /admin/products/product/1/change/ argument must be int or float

When i use the models.DecimalField and specify (max_digits=10, decimal_places=2), I receive the error TypeError at/admin/products/product/1/change/argument must be int or float when trying to access it through the admin page.
If i remove (max_digits=10, decimal_places=2) and just put in a TextField() it works, therefore models.DecimalField(max_digits=10, decimal_places=2) throws and error but models.TextField() doesnt.
Any idea?
from django.db import models
class Product(models.Model):
title = models.CharField(max_length=150)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
the error:
TypeError at /admin/products/product/1/change/
argument must be int or float
Request Method: GET
Request URL: http://localhost:8000/admin/products/product/1/change/
Django Version: 2.2.2
Exception Type: TypeError
Exception Value:
argument must be int or float
Exception Location:
to fix this error delete your pychache from migrations folder and also from your project folder but leave the init.py file as it is. also delete the sqlite database file (db.sqlite3) and then quit the server (if running), after that run the following command (in cmd or in your terminal )
python manage.py makemigrations
python manage.py migrate
then you need to create the superuser again. by following commmand
python manage.py createsuperuser (fill all the entries and then run the server)
good luck :)
Solved it, by increasing the max_digits it worked!
Thanks for your help.

Error with sample code from Django docs

I copied the full example code from: [customizing admin user][1] (part of the django documentation), but when I run it the django will not came out error,but when i add a user ,the django will the came out following error .
I have not changed any code for the example,and setting follow up the document.
follow up link is example:
https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#a-full-example
Error:
IntegrityError at /admin/app01/myuser/add/
NOT NULL constraint failed: app01_myuser.last_login
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/app01/myuser/add/
Django Version: 1.8.5
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: app01_myuser.last_login
Exception Location: /Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 318
There is clearly a discrepancy between the custom user model you are using from the Django sample code and the definition of the table it represents in database. The error is from the database saying the last_login column of the app01_myuser table has a NOT NULL constraint on it and you are trying to create a user with that field NULL.
Your MyUser model contains the last_login field inherited from AbstractBaseUser. Here is the definition of last_login from the AbstractBaseUser class:
last_login = models.DateTimeField(_('last login'), blank=True, null=True)
Based on that definition of last_login, the NOT NULL constraint should not exist in your database.
Make sure your database is up to date by running migrations. Watch for any errors that occur when running the migrations.
You can also check the app01 migrations code to try to see when and why app01_myuser was created with the NOT NULL constraint in the first place.

How to fix a Database Error and ghost migration error in Django?

I am getting an DatabaseError saying no column named playlist exists and I'm trying to figure out how to fix it. I'm using South. I deleted the old files in the my migrations folder and ran:
python manage.py schemamigration app_name --initial
python manage.py migrate reserve
I get this error when I do that:
south.exceptions.GhostMigrations:
! These migrations are in the database but not on disk:
<reserve: 0002_initial>
! I'm not trusting myself; either fix this yourself by fiddling
! with the south_migrationhistory table, or pass --delete-ghost-migrations
! to South to have it delete ALL of these records (this may not be good).
I'm not sure how to get rid of this error, since in my migrations folder I only have init.py(c) and 0001_initial.py(c); I don't have 0002 migration file anymore.
When I try runserver and click "add playlist" in the admin, this is when I get the DatabaseError. If it helps, my models.py is:
class UserProfile(models.Model):
user = models.OneToOneField(User)
def __unicode__(self):
return self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
class Playlist(models.Model):
playlist = models.CharField('Playlist', max_length = 2000, null=True, blank=True)
def __unicode__(self):
return self.playlist
class Video(models.Model):
video_url = models.URLField('Link to video', max_length = 200, null=True, blank=True)
def __unicode__(self):
return self.video_url
class UserPlaylist(models.Model):
profile = models.ForeignKey(User)
playlist = models.ForeignKey(Playlist)
def __unicode__(self):
return self.playlist
class Videoplaylist(models.Model):
video = models.ForeignKey(Video)
playlist = models.ForeignKey(UserPlaylist)
def __unicode__(self):
return self.playlist
Any advice on how to fix this?
Just run
python manage.py migrate reserve --delete-ghost-migrations
This should remove non existing migration from the database table south_migrationhistory.
First, you should work out what happened to get the db and filesystem out of sync.
Then, if appropriate, you can do
python manage.py migrate reserve --ignore-ghost-migrations
or
python manage.py migrate reserve --delete-ghost-migrations
as Aidas said, whichever seems more appropriate. The ignore option is probably less risky, although something has already gone astray for you to get to this state.
South stores migration information in the database too, in a table called "migrations". [ I think thats the table name; writing this from memory ].
You need to clear that table out.
Note
Once you clear that table out, you have to start the migrations again from scratch; right from the initial migration.
It would be a good idea to make a copy of your database as-is before you do this. I assume that your code is already version controlled.
Usually this error happens because, you created a migration file and did the migration then, that migration file was deleted from your file system(disk)
So you have changes in your database caused by a migration that no longer exists.
Depending on whether you deleted the migration file file by choice, what you can do; is go ahead and also delete the changes from the database.
Start the python shell;
$ python manage.py shell
>>from south.models import MigrationHistory
>>MigrationHistory.objects.filter(migration='0002_initial').delete()
That will have deleted the 0002 migration from the db.
You can now go ahead and create/recreate the migration you want.
Goodluck,
Komu.
Just run the command where manage.py file is present in your directory
./manage.py migrate appname --delete-ghost-migrations

Categories

Resources