Django Model Modification missing field: - django

I am trying to add and "orders" field to a user that is a foreignkey to a class Order. Order has a foreignkey to a class OrderItem. OrderItem has a OneToOneField to another app's class Store Item. I used south to migrate the database. I do not believe the error is in the way the database was migrated. I get an operational error, "error: no such table: webstore_storeitem". Any help would be greatly appreciated. Thank you.
from django.contrib.auth.models import User
from django.db import models
from loginRouter import *
class OrderItem(models.Model):
itemCost = models.DecimalField(max_digits=16,decimal_places=2)
itemQuantity = models.IntegerField()
itemID = models.OneToOneField('webstore.StoreItem')
def __unicode__(self):
return self.itemID.itemName
class Order(models.Model):
orderDate = models.DateTimeField('Order Date')
shippingCost = models.DecimalField(max_digits=16,decimal_places=2)
totalCost = models.DecimalField(max_digits=16,decimal_places=2)
item = models.ForeignKey(OrderItem)
def __unicode__(self):
return unicode(self.item)
class UserProfile(models.Model):
user = models.OneToOneField(User)
confirmation_code = models.CharField(max_length=128)
reset_code = models.CharField(max_length=128)
address_lineOne = models.CharField(max_length=128)
address_lineTwo = models.CharField(max_length=128)
city = models.CharField(max_length=128)
State = models.CharField(max_length=128)
zipCode = models.CharField(max_length=10)
orders = models.ForeignKey(Order)
def __unicode__(self):
return self.user.username
What I did with south:
before Change:
$./manage.py schemamigration login --initial
after change:
$./manage.py schemamigration login --auto
$./manage.py migrate login --fake
$./manage.py migrate login
webstore.Models:
from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
class StoreCategory(models.Model):
categoryName = models.CharField(max_length=128)
def __unicode__(self):
return self.categoryName
class StoreItem(models.Model):
category = models.ForeignKey(StoreCategory)
itemName = models.CharField(max_length=128)
itemNameid = models.CharField(max_length=128)
description = models.CharField(max_length=2048)
price = models.DecimalField(max_digits=16,decimal_places=2)
quantity = models.IntegerField(default=0)
picture = ProcessedImageField(upload_to='avatars',
processors=[ResizeToFill(250, 185)],
format='JPEG',
options={'quality': 60})
featured_picture = ProcessedImageField(upload_to='avatars',
processors=[ResizeToFill(800, 300)],
format='JPEG',
options={'quality': 60})
isFeatured = models.BooleanField(default=False)
def __unicode__(self):
return self.itemName

The Problem was that each app was using a separate database. I merged them and this resolved the problem I was having.

Related

Django: Linking Models in different apps gives circular import error

I have two apps in my project names quiz_app_teacher and accounts
many models from these files are connected with each other, but when i try to migrate I get this error
File "F:\self\quiz_site\quiz_app_teacher\models.py", line 2, in
from accounts import models as account_models File "F:\self\quiz_site\accounts\models.py", line 13, in
class Student(models.Model): File "F:\self\quiz_site\accounts\models.py", line 15, in Student
quizzes = models.ManyToManyField(quiz_models.Quiz) AttributeError: partially initialized module 'quiz_app_teacher.models' has no
attribute 'Quiz' (most likely due to a circular import)
quiz_app_teacher/models.py
from django.utils import timezone
from accounts import models as account_models
from django.db import models
# Create your models here.
ANSWER_CHOICES = (
('A', 'A'),
('B', 'B'),
('C','C'),
('D','D'),
)
class Quiz(models.Model):
#https://www.sankalpjonna.com/learn-django/the-right-way-to-use-a-manytomanyfield-in-django
name=models.CharField(max_length=250)
quiz_id = models.CharField(max_length=300,)
created_date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(account_models.User, on_delete=models.CASCADE,related_name='quizzes')
#Using related_names Author.quizzes.all()
#will list all the quizzes which are made by that author.
course = models.ForeignKey(account_models.Course, on_delete=models.CASCADE, related_name='quizzes')
def save(self, *args, **kwargs):
#override default save method to do something before saving object of model
if not self.quiz_id:
self.quiz_id = self.name+"-"+self.created_date.strftime("%M%S") #TODO:Edit this
super(Quiz, self).save(*args, **kwargs)
def __str__(self):
return self.name
class result(models.Model):
#quiz=models.OneToOneField(Quiz,on_delete=models.CASCADE)
student=models.ForeignKey(account_models.Student , on_delete=models.CASCADE,related_name='my_results')#maybe use account_models.User
quiz=models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='results')
points=models.IntegerField()
def __str__(self):
return f"Student name: { str(self.student)} Points:{ str(self.points)}"
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions')
#quiz=models.ForeignKey(Quiz, on_delete=models.CASCADE)
question=models.CharField(max_length=300,)
A = models.CharField(max_length=200,)
B = models.CharField(max_length=200,)
C = models.CharField(max_length=200,)
D = models.CharField(max_length=200,)
answer = models.CharField(max_length=200,choices=ANSWER_CHOICES,default='A')
question_number=models.IntegerField()
def __str__(self):
return self.question
accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
import quiz_app_teacher.models as quiz_models
# Create your models here.
class Course(models.Model):
name = models.CharField(max_length=30)
Year=models.IntegerField()
def __str__(self):
return self.name
class User(AbstractUser):
is_teacher = models.BooleanField(default=False)
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
quizzes = models.ManyToManyField(quiz_models.Quiz)
course = models.ForeignKey(Course,on_delete=models.CASCADE, related_name='class_students')
def __str__(self):
return self.user.username
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
quizzes = models.ManyToManyField(quiz_models.Quiz)
def __str__(self):
return self.user.username
If i try to define relations using
quizzes = models.ManyToManyField(to='quiz_models.Quiz')
SystemCheckError: System check identified some issues:
ERRORS: accounts.Student.quizzes: (fields.E300) Field defines a
relation with model 'quiz_models.Quiz', which is either not installed,
or is abstract. accounts.Student.quizzes: (fields.E307) The field
accounts.Student.quizzes was declared with a lazy reference to
'quiz_models.quiz', but app 'quiz_models' isn't installed.
accounts.Student_quizzes.quiz: (fields.E307) The field
accounts.Student_quizzes.quiz was declared with a lazy reference to
quiz_models.quiz', but app 'quiz_models' isn't installed.
You can remove your imports and refer to your ForeignKey models like so:
models.ForeignKey('account_models.Course', ...)
This should allow you to run your migrations without a circular import
https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ForeignKey
Edit from OP:
Update: I fixed it by running migrations for both files simultaneously. python manage.py makemigrations accounts quiz_app_teacher

Django : change the id with another field in the views page

How do I tell to Django to replace the Column type_id to the name field in the views (html page).
and here I have foreignkey, it gave me id (type_id), and this screentshot of fabrication class:
the column type_id is comming from the composant_type class,
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.base import Model
from CentreCout.models import CentreCoutDB
class fiche(models.Model):
centre_cout = models.CharField(max_length=150)
number = models.CharField(max_length=100)
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class unite(models.Model):
name = models.CharField(max_length= 150, unique=True)
def __str__(self):
return self.name
class composant_type(models.Model):
name = models.CharField(max_length=150, unique=True )
def __str__(self):
return f"({self.name})"
class composant_fab(models.Model):
type = models.ForeignKey(composant_type, to_field='name', on_delete=models.CASCADE)
name = models.CharField(max_length=150, unique=True)
def __str__(self):
return f"({self.name})"
class fabrication(models.Model):
grade = models.ForeignKey(fiche, to_field='name',on_delete=models.CASCADE)
type = models.ForeignKey(composant_type, on_delete=models.CASCADE, blank=True, null=True)
composant = models.ForeignKey(composant_fab , to_field='name', on_delete=models.CASCADE, null=True, blank=True)
unite = models.ForeignKey(unite, to_field='name',on_delete=models.CASCADE)
composant_value = models.FloatField(blank=True, null=True)
def __str__(self):
return f"({self.grade}-{self.composant}-{self.composant_value}-{self.unite})"
views.py
from django.shortcuts import render
from django import views
from django.http import HttpResponse
from .models import *
import pandas as pd
def fabrications(request):
lesfichestab = fiche.objects.all()
fabricationtab = fabrication.objects.all().values()
df = pd.DataFrame(fabricationtab)
context = {
'lesfichestab':lesfichestab,
'fabricationtab':df.to_html()
}
return render(request,'fabrications/fabricationpage.html', context)
Note: I use Pandas method, because i have to do some Filtering and pivoting of the table.
I get an answer from here :
Django with Pandas accessing ForeignKey
admin_data = pd.DataFrame.from_records(
administrations.values(
"id",
"study__name", # <-- get the name through the foreign key
"url_hash",
)
).rename(
columns={
"id": "administration_id",
"study__name": "study_name",
"url_hash": "link",
}
)

Cannot access field in Django Graphene

The field which is specified in my models file is not included in the GraphiQL, I have tried to rename the field, delete it and define it again, even changing the type of field also updating the graphene-django package. None of these I have mentioned didn't work. The name of the field I can't get is named book
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from books.models import Book
class Borrowing(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
book = models.OneToOneField(Book, null=True, on_delete=models.CASCADE)
date = models.DateTimeField(default=timezone.now)
returned = models.BooleanField(default=False)
date_borrowed = models.CharField(blank=True, null=True, max_length=50)
date_returned = models.CharField(blank=True, null=True, max_length=50)
class Meta:
ordering = ['-date']
def __str__(self):
return f'{self.user.username} borrowed {self.book.title}'
schema.py
import graphene
from .mutations.borrowings import *
from backend.functions import pagination
PAGE_SIZE = 12
class BorrowingMutation(graphene.ObjectType):
borrow_book = BorrowBook.Field()
return_book = ReturnBook.Field()
class BorrowingQuery(graphene.ObjectType):
borrowings = graphene.List(BorrowingType)
users_borrowings = graphene.List(BorrowingType, page=graphene.Int())
def resolve_borrowings(self, info):
return Borrowing.objects.all()
def resolve_users_borrowings(self, info, page):
user = info.context.user
borrowings = Borrowing.objects.filter(user=user, returned=False)
borrowings = pagination(PAGE_SIZE, page, borrowings)
return borrowings
Type
class BorrowingType(DjangoObjectType):
class Meta:
model = Borrowing

Django Tabular in Line example

I really need somebody to explain/show me how I can achieve a TabularInline display in the django admin console of my example. Could somebody help me out?
My models are as follows:
from django.db import models
class Player(models.Model):
player_id = models.IntegerField(primary_key=True)
team = models.ForeignKey(Team)
player_name = models.CharField(max_length=140)
position = models.CharField(max_length=10)
def __str__(self):
return '%s' % (self.player_name)
class MatchdayStats(models.Model):
MATCHDAY_STATS_ID = models.AutoField(primary_key=True)
appeared = models.BooleanField(default=False)
goal = models.IntegerField(default=0)
minutes_under_60 = models.BooleanField(default=False)
minutes_60 = models.BooleanField(default=False)
assist = models.IntegerField(default=0)
def __str__(self):
return '%s' % (self.MATCHDAY_STATS_ID)
class PlayerGameweekStats(models.Model):
PLAYER_GAMEWEEK_ALLSTATS_ID = models.AutoField(primary_key=True)
player = models.ForeignKey(Player)
gameweek = models.ForeignKey('fixturesresults.Gameweek')
matchday_stats = models.ForeignKey(MatchdayStats)
def __str__(self):
return '%s (gw=%s,msid=%s)' % (self.player.player_name,self.gameweek.GAMEWEEK_ID,self.matchday_stats.MATCHDAY_STATS_ID)
I would like there to be a tabular display for the PlayerGameweekStats model, where you can enter MatchdayStats fields for each player.
The admin code below causes a Foreign Key error <class 'playerteamstats.models.MatchdayStats'> has no ForeignKey to <class 'playerteamstats.models.PlayerGameweekStats'>
class StatsInLine(admin.TabularInline):
model = MatchdayStats
class PlayerGameweekStatsAdmin(admin.ModelAdmin):
list_display = ('player', 'gameweek')
exclude = ('gameweek')
inlines = [
StatsInLine,
]
admin.site.register(PlayerGameweekStats, PlayerGameweekStatsAdmin)
To build TabularInline models need to be connected with ForeignKey.
From Django docs example:
models.py:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=100)
admin.py:
from django.contrib import admin
class BookInline(admin.TabularInline):
model = Book
class AuthorAdmin(admin.ModelAdmin):
inlines = [
BookInline,
]
In you case you need to have ForeignKey to PlayerGameweekStats in MatchdayStats.

how to populate django models randomly

I am following a tutorial online for Django. The presenter loads in random data as follows:
for i in xrange(100): Vote(link = Link.objects.order_by('?')[0],voter=a).save()
From what I could understand, it goes from 0 to 100 and creates a new vote. The vote object has a link object. I don't understand what the order_by('?') means.
Here is the model.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count
class LinkVoteCountManager(models.Manager):
def get_query_set(self):
return super(LinkVoteCountManager, self).get_query_set().annotate(
votes=Count('vote')).order_by("-votes")
class Link(models.Model):
title = models.CharField("Headline", max_length=100)
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now=True)
rank_score = models.FloatField(default=0.0)
url = models.URLField("URL", max_length=250, blank=True)
description = models.TextField(blank=True)
with_votes = LinkVoteCountManager()
objects = models.Manager()
def __unicode__(self):
return self.title
class Vote(models.Model):
voter = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __unicode__(self):
return "%s voted %s" %(self.voter.username, self.link.title)