Cannot import name ... from partially initialized module - django

For a few days, projects.models has been importing a model from companies.models
I added a line to import a model in reverse, from companies.models to projects.models - hit save - and was given this error
This error says projects.models cannot import from companies.model - even though it's been doing it for the past few days
if I delete the line that caused the error in the other app (companies.models), the error still remains
companies - models.py
from projects.models import (projects)
class companies(models.Model):
fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE)
name = models.CharField(max_length=100, verbose_name="Name")
def __str__(self):
return self.name
class Meta:
ordering = ('id', )
projects - models.py
from companies.models import (companies) {CAUSED THE ERROR}
class projects(models.Model):
fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE)
name = models.CharField(max_length=100, verbose_name="Name")
def __str__(self):
return self.name
class Meta:
ordering = ('id', )
Why after reverting it to how it's been for the last few days by removing the line causing the error, does it no longer work?

Related

NOT NULL constraint failed: shipping_ship.user_id Django

So I'm working on a shipping website with the django rest framework. The website brings two to four people together so they can easily ship their goods together at the same time. But I'm facing a major stumbling block on the views where user book a shipping the code is below.
models.py
from django.db import models
from django.contrib import get_user_model
User = get_user_model()
class Container(models.Model):
container_type = models.Charfield(max_length = 30, blank=False, null = False)
max_users = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places =2, default=0, blank=True, null=True)
users = models.ManyToManyField(User)
class Ship(models.Model):
container = models.ForeignKey(Container, related_name='cont', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='shipper', on_delete=models.CASCADE)
location = (
('France', 'France'),
)
from_location = models.CharField(max_length=30, choices=location, blank=False, null=False)
to_location = (
('Lagos', 'Lagos'),
('Abuja', 'Abuja'),
('Abeokuta', 'Abeokuta'),
('Osun', 'Osun'),
)
to_location = models.CharField(max_length=30, choices=to_location, blank=False, null=False)
date_leaving = models.DateField(auto_now=False)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True)
def __str__(self):
return self.user
then my serializer.py file
from rest_framework import serializers
from .models import Container, Ship
class ContainerSerializer(serializers.ModelSerializer):
class Meta:
model = Container
fields = '__all__'
class MiniContainerSerializer(serializers.ModelSerializer):
class Meta:
model = Container
fields =['container_type', 'price']
class ShipSerializer(serializers.ModelSerializer):
class Meta:
model = Ship
fields = '__all__'
read_only_fields = ('user', 'price')
class MiniShipSerializer(serializers.ModelSerializer):
class Meta:
model = Ship
fields = ['container', 'from_location', 'to_location']
and now my views.py file which I have issues with
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from rest_framework.generics import ListCreateAPIView, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView
from .serializers import ContainerSerializer, MiniContainerSerializer, ShipSerializer, MiniShipSerializer
from rest_framework import permissions, status
from rest_framework.response import Response
from .models import Container, Ship
class ShipAPI(ListCreateAPIView):
serializer_class = ShipSerializer
def get_queryset(self):
user = self.request.user
queryset = Ship.objects.filter(user=user)
return queryset
def Book_shipping(self, request, *args, **kwargs):
user = request.user
container = get_object_or_404(Container, pk=request.data['container'])
if container.users.count() >= container.max_users:
return Response('container already full')# here i'm trying to set limits so the users joining each container won't surpass the max users.
cont = container(users=user)
cont.save()
from_location = (request.data['from_location'])
to_location = (request.data['to_location'])
date_leaving = int(request.data['date_leaving'])
price = container.price / container.max_users
cart = Ship(container=container, user=user, from_location=from_location, to_location=to_location, date_leaving=date_leaving, price=price)
cart.save()
serializer = ShipSerializer(cart)
data ={'message': 'shipping successfully created',
'data':serializer.data}
return Response(data=data, status=status.HTTP_201_CREATED)
and then after testing the endpoint it returns this error:
IntegrityError at /Shipping/Ship/
NOT NULL constraint failed: shipping_ship.user_id
I've tried debugging and looking at it over and over again can someone please help me? Thanks in advance. And yes I've tried deleting migrations and the database.
As your Container model have a ManyToMany relationship with the User model.
So it may not work like cont = container(users=user)
For me it worked like this:
cont = container.users.add(user)
cont.save()

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

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

How to access variables from foreign models in django

I just started out django and python so bear with me. (Just a newbie)
I have 3 models Programme, Module and Lecture.
Programme has a variable 'code' which is a foreign key to module.
Module has in turn also a variable 'code' which is a foreign key to lecture.
In lecture I have implemented a function to get dynamic path for uploading files based on the 'code' of programme, 'code' of module and 'title' of lecture.
Here is a snippet of my models.py
from django.db import models
class Programme(models.Model):
code = models.CharField(blank=True, max_length=20, primary_key=True)
title = models.CharField(blank=True, max_length=120)
synopsis = models.TextField(blank=True)
pub_date = models.DateTimeField(blank=True, auto_now=False, auto_now_add=True)
def get_programme_code(self):
return self.code
def __str__(self):
return self.title
class Module(models.Model):
code = models.CharField(blank=True, max_length=20, primary_key=True)
programme = models.ForeignKey(Programme, on_delete=models.CASCADE)
title = models.CharField(blank=True, max_length=120)
synopsis = models.TextField(blank=True)
pub_date = models.DateTimeField(blank=True, auto_now=False, auto_now_add=True)
def get_module_code(self):
return self.code
def __str__(self):
return self.title
class Lecture(models.Model):
def get_upload_to(self):
return 'uploads/%s/%s/%s/%s' % (Programme().get_programme_code(),Module().get_module_code,self.title,filename)
title = models.SlugField(max_length=100)
module = models.ForeignKey(Module, on_delete=models.CASCADE)
lecture_pdf = models.FileField(upload_to=get_upload_to)
lecture_video = models.FileField(upload_to=get_upload_to)
def __str__(self):
return self.title
I know that there is something wrong with my code by the way of accessing 'code's from programme and modules but I cannot figure it out.
And here is a snippet of my unit testing of the models.
from django.test import TestCase
from module_content.models import Programme, Module, Lecture
from django.utils import timezone
from django.core.urlresolvers import reverse
class ProgrammeTest(TestCase):
def create_programme(self, code="E318", title="Computer Science", synopsis="Englobes all computer related fields"):
return Programme.objects.create(code =code, title=title, synopsis=synopsis, pub_date=timezone.now())
def test_programme_creation(self):
t = self.create_programme()
self.assertTrue(isinstance(t, Programme))
self.assertEqual(t.__str__(), t.title)
def test_get_programme_code(self):
t = self.create_programme()
self.assertEqual(t.get_programme_code(), t.code)
class ModuleTest(TestCase):
def create_module(self, code="CSE2233", title="Computer Networks", synopsis="About data transmission"):
v = ProgrammeTest().create_programme()
return Module.objects.create(code=code, programme=v, title=title, synopsis=synopsis, pub_date=timezone.now())
def test_module_creation(self):
t = self.create_module()
self.assertTrue(isinstance(t, Module))
self.assertEqual(t.__str__(), t.title)
class LectureTest(TestCase):
def create_lecture(self, title="Lecture 1"):
t = ModuleTest().create_module()
return Lecture.objects.create(title=title, module=t)
def test_lecture_creation(self):
s = self.create_lecture()
self.assertTrue(isinstance(s, Lecture))
self.assertEqual(s.__str__(), s.title)
def test_get_upload_to(self):
s = self.create_lecture()
self.assertEqual( s.get_upload_to(), 'uploads/E318/CSE2233/lecture-1')
I put the field of title for lecture to be a slugfield, so does django put it automatically as a slug ?
I tried the slugfield and it just return the title as "Lecture 1" instead of "lecture-1", or maybe I'm missing something.
So how can I access the foreign keys from the models and test it that the dynamic upload path is working properly?
I just needed to access the other models by their foreign keys such as self.module.programme.code - to retrieve the code of the programme.

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)