Foreign key constraint error on Django app - python

I'm trying to have this third class noticeTime be constrained to the foreign key email. I am using the same syntax that worked for the 2nd class location, but when I use it on noticeTime it throws an error:
Exception Value: no such column: setupNotifications_noticetime.email_id
Here is the code:
from django.db import models
# Create your models here.
from django.db import models
class email(models.Model):
email = models.CharField(max_length=200)
def __unicode__(self):
return self.email`
class location(models.Model):
email = models.ForeignKey(email)
zip_code = models.CharField(max_length=5)
def __unicode__(self):
return self.zip_code
class noticeTime(models.Model):
email = models.ForeignKey(email)
time = models.CharField(max_length=200)
def __unicode__(self):
return self.time
here is admin.py:
from django.contrib import admin
# Register your models here.
from setupNotifications.models import email
from setupNotifications.models import location
from setupNotifications.models import noticeTime
admin.site.register(email)
admin.site.register(location)
admin.site.register(noticeTime)
I'm using the sqlite database

Perhaps your problem is that you ran syncdb, assuming that it would alter the table to match your model change. Unfortunately, it does not do that. There are some separate tools available, such as South, which can help with database migrations.

Related

Why makemigrations in django doesn't work?

I wanted to insert into my database from an Excel file. So I created a model in my models.py file.
models.py
from django.db import models
class Materiau(models.Model):
designation = models.CharField(max_length=128)
norme = models.CharField(max_length=128)
temperature = models.CharField(max_length=128)
epaisseur = models.CharField(max_length=128)
symbole = models.CharField(max_length=128)
rho = models.FloatField(default=0.0)
E = models.FloatField(default=0.0)
sigy = models.FloatField(default=0.0)
Etan = models.FloatField(default=0.0)
def __str__(self):
return self.designation
Then I created a Commands file :
Path : my_app/management/commands/update_database.py
from django.core.management.base import BaseCommand
import pandas as pd
from DataMat.models import Materiau
from sqlalchemy import create_engine
class Command(BaseCommand):
def handle(self, *args, **options):
df = pd.read_excel('dataframe.xlsx')
engine = create_engine('sqlite:///db.sqlite3')
df.to_sql(Materiau._meta.db_table, if_exists='replace', con=engine, index=True)
Then when I run python manage.py update_database I can see the database being updated in my db.sqlite3 file.
But when I run the makemigrations I get no changes detected and I can't see my database in the Django admin section.
This is the error I get from Django : no such column: DataMat_materiau.id I don't understand because when I look into my database I can see an index but Django doesn't seem to recognize it.
Also in my update_database.py file, I have this message Access to a protected member _meta of a class.
Does anyone have an idea on how to fix this?

AttributeError at /admin/student/student_record/

I updated my django model, for my student app, it now looks like this
from django.db import models
class Student_Record(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
address = models.CharField(max_length=500)
gpa = models.FloatField()
def __str__(self):
return str(self.student_id) + ", " + self.first_name
there used to be an IntegerField, student_id but I removed it. I made the migrations, and everything runs fine, but when I visit the django admin panel, to manually update the database records, I get the following error
does anyone know what's going on?
I registered the model, in admin.py
from django.contrib import admin
from .models import Student_Record
admin.site.register(Student_Record)
Look at your __str__ method it still references student_id.
You should search for the field name in your whole project, there might be other occurrences elsewhere.

how to avoid circular django model import?

I have these models below
# user profile models file
from ad.models import FavoriteAd
class UserProfile(models.Model):
def get_user_favorite_ad(self):
return FavoriteAd.objects.filter(fav_user=self)
# ad models file
from user_profile.models import UserProfile
class FavoriteAd(models.Model):
fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)
I have tried using these but it give me the NameError UserProfile not found
# ad models files
class FavoriteAd(models.Model):
fav_user = models.ForeignKey('user_profile.UserProfile', blank=False, on_delete=models.CASCADE)
Also tried these as well still got error that model are not ready
# ad models files
from django.apps import apps
UserProfile = apps.get_model('user_profile', 'UserProfile')
class FavoriteAd(models.Model):
fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)
You are using FavoriteAd inside get_user_favorite_ad method of
UserProfile model
Thats the reason you are unable to import it in FavoriteAd and this is causing circular import.
For fetching favorite ads of that user, Use favoritead_set to get related objects
# remove that import as well
# from ad.models import FavoriteAd
class UserProfile(models.Model):
def get_user_favorite_ad(self):
return self.favoritead_set.all()

Unable to migrate Django models

So I'm trying to automatically assign the current logged in user to a variable in my model. I think this make sense but I'm not able to migrate the models and it is going me this error.
models.py:
from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank='True')
def __str__(self):
return self.user.username
class UserPosts(models.Model):
post_title = models.CharField(max_length=100,unique=True)
post_sub_title = models.CharField(max_length=250,unique=False)
post_author = models.ForeignKey('User',User.username)
post_date = models.DateField(default=date.today,blank=True)
post_body = models.TextField(max_length=1000,unique=False)
def __str__(self):
return str(self.post_title)
The Error:
ValueError: Cannot create form field for 'post_author' yet, because its related model 'User' has not been loaded yet
Remove the quotation from this line:
post_author = models.ForeignKey('User',User.username)
It should be like this:
post_author = models.ForeignKey(User,User.username)
I think the problem is this:
from django.contrib.auth.models import User
post_author = models.ForeignKey('User',User.username)
Your ForeignKey want's to use the attribute 'username' of the imported User. Not of your User object when related.
I think I just deleted the migrations and then migrated again from scratch...

NameError at / name 'article_finish_date' is not defined

So I am trying to create a custom Manager that extends the default one and I am getting an error that for the life of me I cannot fix. I've read all the django docs and can't see what I've done wrong!
ERROR:
NameError at /
name 'article_finish_date' is not defined
Here is my models.py
import datetime
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class ArticleManager(models.Manager):
def get_queryset(self):
return super(ArticleManager, self).get_queryset().filter(article_finish_date==None)
class Article(models.Model):
article_name_text = models.CharField(max_length=200)
article_creation_date = models.DateTimeField('date created')
article_publish_date = models.DateTimeField('date published', null=True, blank=True)
article_finish_date = models.DateTimeField('date finished', null=True, blank=True)
def __str__(self):
return self.article_name_text
actives = ArticleManager()
I have tried filtering by all the different values of the Article model, however the same issue occurs. I have tried both migrated and makemigrations, however no progress has been made.
Many thanks in advance, ask if you need more details!
The error is in this part:
.filter(article_finish_date==None)
Python is trying to evaluate the expression article_finish_date==None, except article_finish_date hasn't been defined yet. Instead, you want to use a single =
.filter(article_finish_date=None)

Categories