Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to read link from beautifulsoup output python
I am trying to pass a link I extracted from beautifulsoup. import requests r = requests.get('https://data.ed.gov/dataset/college-scorecard-all-data-files-through-6-2020/resources') soup = bs(r.content, 'lxml') links = [item['href'] if item.get('href') is not None else item['src'] for item in soup.select('[href^="http"], [src^="http"]') ] print(links[1]) This is the link I am wanting. Output: https://ed-public-download.app.cloud.gov/downloads/CollegeScorecard_Raw_Data_07202021.zip Now I am trying to pass this link through so I can download the contents. # make a folder if it doesn't already exist if not os.path.exists(folder_name): os.makedirs(folder_name) # pass the url url = r'link from beautifulsoup result needs to go here' response = requests.get(url, stream = True) # extract contents with zipfile.ZipFile(io.BytesIO(response.content)) as zf: for elem in zf.namelist(): zf.extract(elem, '../data') My overall goal is trying to take the link that I webscraped and place it in the url variable because the link is always changing on this website. I want to make it dynamic so I don't have to manually search for this link and change it when its changing and instead it changes dynamically. I hope this makes sense and appreciate any help I can get. If I manually enter my code as the following I know it works url = r'https://ed-public-download.app.cloud.gov/downloads/CollegeScorecard_Raw_Data_07202021.zip' If I can get my code to pass that exactly … -
filtering items on current page
how can I apply sorting to the current page, if I am on a page of a certain category and want to sort by price, it will return me to the page with all products sorted by price template for main page of store <form name="selectForm" action="{% url 'shop' %}" method="get"> <label for="orderby"></label> <select name="orderby" id="orderby" onchange="selectForm.submit();"> <option value="">default</option> <option value="price">price: $ - $$</option> <option value="-price">price: $$ - $</option> <option value="collection">collection</option> <option value="-collection">collection2</option> </select> <input type="submit" class="d-none" value="submit"> </form> template for category {% for cat in shoes_subcategories %} <li><a href="{% url 'shop_category' cat.slug %}">{{ cat.name }}</a></li> {% endfor %} views class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = True model = Item def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) ***context*** return context def get_ordering(self): return self.request.GET.get('orderby', ) class ShopBySubCategory(Shop, ListView): def get_queryset(self): return Item.objects.filter(sub_category__slug=self.kwargs['slug']) class ShopByBrand(Shop, ListView): def get_queryset(self): return Item.objects.filter(brand__slug=self.kwargs['slug']) -
TemplateDoesNotExist for base.html of each app
Here's the structure of my project: project_name/ app1/ templates/ base.html app1/ index.html app2/ templates/ base.html app2/ index.html app3/ templates/ base.html app3/ index.html And in settings.py: TEMPLATES = [ { ... 'DIRS': [BASE_DIR / 'templates/', ], ... }, ] and BASE_DIR is defined as (the default for Django 3.2 on Windows): Path(__file__).resolve().parent.parent None of my index.html files are able to locate their own base.html using {% extends 'appX/base.html' I get TemplateDoesNotExist error. What I'm missing? -
How can I let my users send emails from their gmail account through my django application?
I am building a Django App and I would like users to be able to trigger sending an email from my app to an email they chose using their gmail account as a sender. I know this is doable for one users only by changing the setting in django, but can I do it for multiple users? -
Fetch related and inversely related objects at once - Django
I'm trying to fetch objects in my database using one line with select_related(). Here is my models: class Asset(models.Model): """Store information about an asset.""" is_active = models.BooleanField(default=True) rank = models.PositiveIntegerField() class AssetMarketData(models.Model): """Store market data of an asset.""" asset = models.OneToOneField(Asset, related_name="market_data", on_delete=models.CASCADE) class AssetQuote(models.Model): """Store quotes of an asset.""" asset = models.ForeignKey(Asset, related_name="quote", on_delete=models.CASCADE) I want to retrieve all Asset objects using select_related() like this: assets = Asset.objects.order_by('rank').select_related('market_data', 'quote') However, this is not possible because quote is a reverse relationship. I can access the quotes using: assets[0].quote.all() But I can only do it for one Asset at a time which I want to avoid. prefetch_related() can only retrieve inversely related objects so it doesn't help. So I would like to know how to retrieve all related AssetQuote when I select all Asset objects. -
image corrupted after reading image file in chunk
so i am trying to ready image file form django request in chunks, the django filehandler chunks method does not work well for me, so i created a custom on, it works but the end product wasnt what i was expecting, so after reading the files in chunks and putting them together somehow the image get corrupts and i dont have any solution for it. def process_download_with_progress(self, image_file, length): process_recoder = ProgressRecorder(self) print('Upload: Task Started') fs = FileSystemStorage() buffer = io.BytesIO() chunk_size = 0 for chunk in read_chunk(image_file.file, length): chunk_size += 1 buffer.write(chunk) process_recoder.set_progress(chunk_size, length, description=f'uploaded {chunk_size*length} bytes of the file') buffer.seek(0) image = ImageFile(buffer, name=image_file.name) fs.save(image_file.name, content=image) return 'Done' def read_chunk(file_object, chunk_size=125): while True: file = file_object.read(chunk_size) if not file: break yield file so this my code, any help will be appreciated, thanks. -
I'm trying to use tkinter in python but I'm getting an import error [closed]
I'm trying to use tkinter in python but I'm getting an import error.i installed tkinter but did not import tkinter -
function to check if an object exists Django
This is all a little too confusing for me, what I need to do is make a function to check if an object exists on the database (so it's already been created), and if it does, get its ID, store it on a field in a model, lets say value, and then I need made a function called get_name, where i concatinate what I need to do, store it to the field name. Now I need to make it so the code attribute on Order model, is equal to the name attribute. Any suggestions would be welcomed. Also some pointers on weather the code is okay because I wasn't sure how to test it after writing it. What I've done so far: class Order(models.Model): code = models.IntegerField(unique=True) code_year = models.IntegerField class Counter(models.Model): def count(self): value = 0 code = Order.objects.get['code'] if Order.objects.filter(code=code).exists(): value += 1 return value def get_name(self): return str('P' + self.value + Order.code_year) name = models.CharField(max_length=10, validators=[get_name]) value = models.IntegerField(validators=[count]) -
ImportError: attempted relative import beyond top-level package in django
enter image description here enter image description here enter image description here I am trying to use one app model function in other app model function but it show an ImportError. -
How to serve image files from MongoDB in Django
I am building a Django application that stores image files in a mongodb GridFS. I use Djongo to work with the database and followed this example https://www.djongomapper.com/using-django-with-mongodb-gridfs/ to store the images to the DB. So now I can, currently through the admin page, upload images to the DB, which need to be accessed using a URL like this: http://127.0.0.1:8000/files/60fae4884db41b9ad761c8b0 Now I have this in the urls.py urlpatterns = [ ... path('files/<str:fileid>', views.files, name='files'), ] But in View file I don't know how to retrieve the image from the DB: @login_required def files(request, fileid): return response I searched the documentation of Djongo and Django but couldn't find an easy way to do it, any help is appreciated. Note: In the main DB collection only the image file name is stored. In gridfs collection 'files' an ID (the one in the URL), the image name (the only link to the main collection) and other details are stored. And in the 'chunks' collection there is an ID , a files_ID (foreign key to the files ID) and the binary data. -
Django - annotation produces duplicate joins
The following annotation produces duplicates .annotate( **{ f"{key}_bundle_id": F('item__child_link__parent_item__bundle__id'), f"{key}_bundle_name": F('item__child_link__parent_item__bundle__name') } ) Both of these annotations join across a many to many table to get the id and name of the joined table. I would expect this to produce a join, and select both the id and name from the join. Instead it duplicates the join and selects the id from 1 set and the name from the other. Is there a solution to work around this or do annotations always produce their own joins? Here's the sql it generates: SELECT T8.id as x_axis_bundle_id, T12.name as x_axis_bundle_name .... INNER JOIN "item" ON ("gmdts"."item_id" = "item"."id") INNER JOIN "link" ON ("item"."id" = "link"."child_id") INNER JOIN "item" T8 ON ("link"."parent_id" = T8."id") INNER JOIN "bundle" T9 ON (T8."id" = T9."item_id") INNER JOIN "link" T10 ON ("item"."id" = T10."child_id") INNER JOIN "item" T11 ON (T10."parent_id" = T11."id") INNER JOIN "bundle" T12 ON (T11."id" = T12."item_id") -
I need to filter Titles by genre field, I tried to use DjangoFilterBackend, but it didn't work, I don't know, how to create a CustomSearchFilter?
I need to filter Titles by genre field, I tried to use DjangoFilterBackend, but it didn't work, I don't know, how to create a CustomSearchFilter? Views: class GenreViewSet(ModelCVDViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer permission_classes = (IsAdminOrReadOnly,) filter_backends = (DjangoFilterBackend, filters.SearchFilter) filterset_fields = ('name', 'slug') search_fields = ('name', 'slug') lookup_field = 'slug' class TitleViewSet(viewsets.ModelViewSet): queryset = Title.objects.all() serializer_class = TitleSerializer permission_classes = (IsAdminOrReadOnly,) filter_backends = (DjangoFilterBackend, filters.SearchFilter) filterset_fields = ('genre__slug', 'category__slug', 'name', 'year') search_fields = ('=genre__slug', '=category__slug', 'name', 'year') -
Cascade delete of model with GenericForeignKey without using GenericRelation
I'm creating a reusable django app which includes a model with GenericForeignKey which I need to be cascade deleted. This model may be attached to any other. I have no control over target model class as it is outside of the app. This means I can not add GenericRelation field to it and can't force user to add it as target might be in another third-party app. Assuming we have such models (having NO control over Post and PostGroup): class Tag(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() object = GenericForeignKey() class PostGroup(models.Model): title = models.CharField(max_length=255) class Post(models.Model): title = models.CharField(max_length=255) group = models.ForeignKey(PostGroup, on_delete=models.CASCADE) Is there a way to delete Tag in case of PostGroup queryset is being deleted? E.g. not only post_group.delete() but also PostGroup.objects.delete(). -
how can I add a django array element into a js array using an if condition
I have a Django project with data being submitted by form , I am trying to use chart.js to display the data. I need to check whether an array exists() if so then add an item to 'labels' array in 'mycharts.js' . Heres what I have so far django views.py ing1 = request.POST.getlist('ingredients1') ing2 = request.POST.getlist('ingredients2') ing3 = request.POST.getlist('ingredients3') ( I've passed the above into my context ) mycharts.js var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: {chart.js labels: ['{{ing1.0}}', '{{ing2.0}}', {% if ing3|length > 1 %} '{{ing3.0}}', {% endif %}], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], (etc...) if I take out the if statement inside of 'labels' array , then it shows the 'ing1' and 'ing2' headings , but I can't get it to work with this if statement , whats the correct way of doing it. -
Django rest framework and react - CORS issue only on same URLs
I'm using react on the frontend side and Django on the backend. I using corsheaders.middleware.CorsMiddleware ALLOWED_HOSTS = ["127.0.0.1", "localhost"] and for some URLs I have no issue sending a request and for others, I am getting: Access to XMLHttpRequest at 'http://localhost:8000/api/actions' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. error. Working URL: http://localhost:8000/api/profiles/auth-data Not working URL: http://localhost:8000/api/actions method: GET settings.py: """ Django settings for server project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path from corsheaders.defaults import default_headers # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ["GH_BE_SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True PROD = False ALLOWED_HOSTS = ["127.0.0.1", "localhost"] CORS_ALLOW_HEADERS = list(default_headers) + [ "businessId", ] # Application definition # TODO need to check security in PROD ['corsheaders'] … -
How can I query data from two tables in Django, when some of the data is conditional
We have multiple data tables, the 'main' one is Player with the primary key Player Name, which is a foreign key to a few other tables, and a foreign key Team Name which is a foreign key to a table called Team, with Team Name being that primary key. We have this query in SQL: SELECT p.TeamName, AVG(b.G) as avg_games_for_team, AVG(b.OPS) FROM Players as p JOIN batter as b ON p.PlayerName = b.PlayerName GROUP BY p.TeamName ORDER BY avg_games_for_team LIMIT 15; And we can't translate this into Django ORM. I know you're supposed to give some of the code you've tried, but we really aren't able to put anything down into paper. The only thing we can get is something like Players.objects.select_related('Teams').get(TeamName).filter(...) using this as a start. We also know to use .annotate() but can't discover where or how. Thanks! -
django-js-routes resolver not finding url
using https://pypi.org/project/django-js-routes/ along with Vue2 and Inertia.js the resolver.js file is not finding the routes i have included in my JS_ROUTES_INCLUSION_LIST application urls.py from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', views.index, name='index'), path('article/<int:id>/', views.articleDetailsPage, name='article'), ] urlpatterns += staticfiles_urlpatterns() Vue template attempting to call route <template> <div> … <div class="sm:p-6 sm:flex sm:flex-col"> <div v-for="article in articles" :key="article.id" class="sm:text-xl"> <inertia-link :href="route('article', article.id)"> {{article.title}} </inertia-link> </div> </div> … </template> <script> export default { props: [ 'articles', 'num_articles' ], methods: { 'page_name': function() { return 'Articles Page' }, 'route': function(...args) { return window.reverseUrl(...args); }, }, } </script> project urls.py #add articles app urls urlpatterns += [ path('articles/', include('articles.urls')), ] project settings.py # Django JS Routes Inclusion List JS_ROUTES_INCLUSION_LIST = [ 'trends', 'articles:index', 'articles:article', ] I have also tried a settings.py where the list only included the app name, articles, whose urls are not being found error returned in console URL 'article' was not found. The error message is being returned by the django-js-routes resolver.js file -
Failed to connect to remote host when using Stripe webhooks
Created stripe webhook account in Test environmnet and then try "send test webhook"enter image description here -
Django Google log-in/sign up not working even though django-oauth
Following this guide to add google sign-in/sign-up to my django app. Added all the code and it all seemed to be working until the very end when I got this error. Error 400: redirect_uri_mismatch The redirect URI in the request, http://127.0.0.1:8000/accounts/google/login/callback/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/.... However, i visit my credential screen I do see the url correctly reported. What am i doing wrong? -
Gunicorn does not handles connections on Elastic Beanstalk AL2
My gunicorn does not accepts connexion. I'm currently launching gunicorn manually to test why it fails to accept connexion. $ gunicorn --bind :8080 --workers 1 config.wsgi:application --log-level=debug [2021-07-23 16:48:20 +0000] [7943] [INFO] Starting gunicorn 20.1.0 [2021-07-23 16:48:20 +0000] [7943] [DEBUG] Arbiter booted [2021-07-23 16:48:20 +0000] [7943] [INFO] Listening at: http://0.0.0.0:8080 (7943) [2021-07-23 16:48:20 +0000] [7943] [INFO] Using worker: sync [2021-07-23 16:48:20 +0000] [7946] [INFO] Booting worker with pid: 7946 [2021-07-23 16:48:20 +0000] [7943] [DEBUG] 1 workers bash: /opt/python/current/env: No such file or directory This /opt/python/current/env stuff seems to come from old AL1 config but I don't know where it come from. Gunicorn continue to work but without accepting connexions. Here is the output from curl: * Empty reply from server * Connection #0 to host test.skippair.com left intact curl: (52) Empty reply from server * Closing connection 0 -
Database considerations when writing a Django app for personal use only in a local server
I am a Django developer for a startup. The project is about to finish and I will start looking for a new job soon. I would like to use my skills do write a simple app to keep my job search organised and I would like to keep my database running on my localhost. I don't want to spend money and effort hosting the website online as I can simply run it with a local database. The problem is that as I develop my apps I usually nuke my database when some migration didn't go as planned or sometimes when PostgreSQL acts out (as in updates). So I would like to know what are the best options for developing and app with a development database while I have an actual database with valuable data that I don't want to lose. If anybody ever faced this problem I would like to know possible solutions. Thanks! -
Why static files are served locally and not from AWS s3 in my Django project?
I have Django application and I want to serve static and media files from AWS s3 bucket but after configuration only media files are served from s3 and static files are served locally. When I collect static all static files are collected in local staticfiles folder. No files are send to AWS s3 bucket. I had to copy them manually to s3. I use Django==2.1.4, boto3==1.18.3, django-storages==1.11.1 Below I show the configuration in settings.py (some irrelevant parts are removed and I comment STATIC_URL and MEDIA_URL values that I have tried) I tried for example what was advised in this topic Django and S3 Bucket AWS Admin Static files. import os from decouple import config import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = ['yogahouse-ap.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'yogahouse.urls' IMAGEKIT_URL = config('IMAGEKIT_URL') AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = 'eu-central-1' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_STATIC_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'yogahouse.storages.MediaStorage' AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com" AWS_IS_GZIPPED = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL … -
How to keep a message within a string instead of showing it on CMD ? python
What does the channel.basic_consume' function return? how i can access to message using variable i want consumed message and show it in browser? i build django application send message to rabbitmq and consume messsage from it to show message in browser like chat import pika, sys global message def consume(room,username): credentials = pika.PlainCredentials('admin', 'admin') parameters = pika.ConnectionParameters('192.168.1.14',5672,'/', credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.exchange_declare(exchange='topic_exchange', exchange_type='topic') result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue arr= [room,username] binding_key ='.'.join([str(i) for i in arr]) channel.queue_bind(exchange='topic_exchange', queue=queue_name, routing_key=binding_key) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r:%r" % (method.routing_key, body)) channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True) global message #message = channel.start_consuming() return message -
Djngo Signals How to find duplicate in queryset and appoint theme for sender and receiver?
I am using django post_save signals in my BlogComment model and creating duplicate of each object. I want to appoint first duplicate for my sender and second duplicate for my receiver. How to do that in queryset? This queryset for my sender: notifications = Notifications.objects.all().filter(sender=user).order_by('-date') This queryset for my reciver: notifications = Notifications.objects.all().filter(receiver=user).order_by('-date') here is my BlogComment model which creating Notifications objects: class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) #my others fileds #here signals stating def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user commnet_notes = comment.rejected_comment_notes comment_text = comment.comment if sender != blog.author and comment.is_published == "pending": notify = Notifications(blog=blog, sender=sender, receiver=comment.blog.author,text_preview=comment_text[:250], notification_type="New Comment") notify.save() #want appoint this object for receiver in queryset notify2 =Notifications.objects.create(blog=blog, sender=sender, receiver=comment.blog.author, text_preview=comment_text[:250], notification_type="New Comment") notify2.save() #want appoint this object for sender in queryset post_save.connect(BlogComment.user_comment, sender=BlogComment) here my notifications model: class Notifications(models.Model): blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE,blank=True,null=True) blogcomment = models.ForeignKey('blog.BlogComment',on_delete=models.CASCADE, blank=True,null=True) globalnotifications = models.ForeignKey('blog.GlobalNotifications',on_delete=models.CASCADE,blank=True,null=True) NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved'), ('Comment Rejected','Comment Rejected'),('pending post','pending post'),('post approved','post approved'),('post rejected','post rejected'),('global_noti','global_noti')) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.CharField(choices=NOTIFICATION_TYPES,max_length=250,default="New Comment") text_preview = models.CharField(max_length=500, blank=True) help_notes = models.TextField(max_length=1000,default="",blank=True,null=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) is_seen_author_noti = models.BooleanField(default=False) def __str__(self): return … -
Django Admin Selection by Related Tables
I have models named School, Class and Student List. When adding to the student list, there is a class selection. I want to filter these classes by choosing school name and only show classes belonging to that school. How can I do that? When I add on the admin page, only the class selection field comes up. My admin.py file is default for now. How can I filter during this insertion process? Example scenario -> When the add page opens School: "Empty" Class: "Empty because no school has been selected yet" Child: "List of children" -> When a school selected School: "Example School" Class: "Class list of selected school" Child: "List of children" School Model class School(AbstractSchoolBaseModel): city = models.ForeignKey( "country.City", on_delete=models.DO_NOTHING, related_name="city_schools", verbose_name=SchoolStrings.SchoolStrings.city_verbose_name) name = models.CharField( max_length=250, verbose_name=SchoolStrings.SchoolStrings.name_verbose_name) address = models.CharField( max_length=250, verbose_name=SchoolStrings.SchoolStrings.address_verbose_name) website = models.CharField( max_length=250, verbose_name=SchoolStrings.SchoolStrings.website_verbose_name) Class Model class Class(AbstractSchoolBaseModel): school = models.ForeignKey( "school.School", on_delete=models.CASCADE, related_name="classes_school", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( "account.InstructorProfile", on_delete=models.CASCADE, related_name="instructors_school", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) Student List Model class StudentList(AbstractSchoolBaseModel): school_class = models.ForeignKey( "school.Class", on_delete=models.CASCADE, related_name="student_list_class", verbose_name=SchoolStrings.StudentListStrings.school_class_verbose_name ) child = models.ForeignKey( "account.ChildProfile", on_delete=models.CASCADE, related_name="children_class", verbose_name=SchoolStrings.StudentListStrings.child_verbose_name)