Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 500 Internal Server Error only on log in success page
Request URL: http://35.239.95.43:8080/timetracker/login_success/ this is login succes url after providing credentials it has to show login succes page but giving this error.however on localhost everything working fine -
Return erroneous data with serializer error
Got user serializer for insert multiple users at once. class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'username', 'email', 'first_name', 'last_name', 'is_active', ) Passing data from request to serializer to create users payload = [ { "username": "johndoe", "email": "john@doe.com", "first_name": "John", "last_name": "Doe", "is_active": true }, { "username": "janedoe", "email": "jane@doe.com", "first_name": "Jane", "last_name": "Doe", "is_active": true }, { "username": "johndoe", "email": "james@doe.com", "first_name": "James", "last_name": "Doe", "is_active": true } ] While inserting payload via serializer, is_valid returns false because same username used twice in payload. def create_user(request): data = request.data["payload"] serialized_data = CreateUserSerializer(data=data, many=is_many) if serialized_data.is_valid(): serialized_data.save() else: return serialized_data.errors The method above is returns [{'username': [ErrorDetail(string='user with this username already exists.', code='unique')], }] error but not indicates which data is erroneous. Is there a way to detect erroneous data and attach data to serialize error in any way? -
I added In-Reply-To and References in my headers while sending Email through SendGrid, however it doesn't work
So I am sending an email reply through SendGrid and I have a message object something like this: message = { "personalizations": context["personalizations"], "from": {"email": context["sender_email"]}, "subject": context["subject"], "content": [{"type": MimeType.html, "value": context["body"]}], "reply_to": {"email": context["reply_to"]}, "headers": {"In-Reply-To": "<Prev-Message-ID>", "References": "<Prev-Message-ID>", } } sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY")) sg.send(message) Now when I go to the 'Show Original' in Gmail, the email does have References and In-Reply-To in headers. Something like this: Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset=us-ascii Date: Thu, 04 Aug 2022 05:47:05 +0000 (UTC) From: test.Taylor-Hood_b56ef494-4d5e-4568-bcf5- bc68d489f86b@hirecinch.com Mime-Version: 1.0 Message-ID: <3S2bF8n9Rj-0eNQWf172Gw@geopod-ismtpd-4-0> Subject: Hakunamatata!!! Reply-To: 3b0b71af9b8ba94577730eb010f0887e@mailer.local.hirecinch.com In-Reply-To: <CABQc7oqgKENUUAz6Mg4kdS7ZS8Q3Wq95DPNo-O2- 18wyaVaXgw@mail.gmail.com> References: <CABQc7oqgKENUUAz6Mg4kdS7ZS8Q3Wq95DPNo-O2- 18wyaVaXgw@mail.gmail.com> However, the email I send is never appended as a reply and always makes a new thread. What am I doing wrong?? Is it about the subject of the email which I send in reply?? I have tried doing Re: The Subject, but it still doesn't work. I have to display the whole conversation as a thread having sub-threads in my product and I'm stuck. -
set accept-ranges of django app on pythonanywhere
I'm deploying django app to the "pythonanywhere". I have the middleware to set accept-ranges to bytes and it work perfactly well in my localhost, but not in pythonanywhere server. Is there another way to set accept-ranges in my pythonanywhere server? -
Masonite Invalid CSRF token
Invalid CSRF Token raise InvalidCSRFToken("Invalid CSRF Token") After running the command "python craft serve" it is showing this error. -
Create new schema in django migration file
How to create a new schema using Django migration file? I dont see any migrations.CreateSchema() option just like there is migrations.CreateModel() Currently the way I do this is in my migration file I write custom sql: operations = [ migrations.RunSQL('create schema if not exists schema1;'), ] -
django.db.utils.DatabaseError: ORA-00932: inconsistent datatypes: expected - got NCLOB
Getting this error on django-Oracle database while fetchinfg queryset on .distinct() filtering. -
Django Many to many how to give input to 3rd table
class Author(models.Model): name = models.CharField(max_length = 100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length = 100) authors = models.ManyToManyField(Author) def __str__(self): return self.title In [5]: Author.objects.all() Out[5]: <QuerySet [<Author: Shanmukh>, <Author: Shyam>, <Author: sai>, <Author: VICKYS>, <Author: Himayu>, <Author: Himanya>, <Author: Srinivas>, <Author: LASKARATOYIBA>, <Author: ISI>, <Author: JAMI>]> please help in solving this i dont understand how do i give data to 3rd table which is a combination of id bookid and authorid -
Django raises the exception for error wont override for HttpResponse
I am using the Django to create my custom error page handler for 400, 403, 404 ,500. But for some reason, when the page return HttpResponse error, it wont direct me to my django custom error template page, instead of, it shows this. This django can find the url and go in the view function, but we return HttpResponse 404 it is not found. For example, http://127.0.0.1:8000/404/ , this will go to the customize page because Django cannot find this url in our project ### views.py from django.shortcuts import render def page_not_found_view(request, exception): return render(request, 'error.html',status = 404,context = { 'status_code' : 404, 'message' : "The page you were looking for doesn't exist anymore.", 'title' : "Page Not Found" }) def internal_server_error_view(request, *args, **argv): return render(request, 'error.html',status = 500,context = { 'status_code' : 500, 'message' : "500 Internal Server Error.", 'title' : "Internal Server Error" }) def forbidden_error_view(request, exception): return render(request, 'error.html',status = 403,context = { 'status_code' : 403, 'message' : "403 Forbidden Error.", 'title' : "Forbidden Error" }) def bad_request_error_view(request, exception): return render(request, 'error.html',status = 400,context = { 'status_code' : 400, 'message' : "400 Bad Request Error.", 'title' : "Bad Request" }) ### urls.py hanlder400 = "gotani.views.bad_request_error_view" handler404 = … -
Persisting session data across sign up
My website has a need similar to this question, but slightly different. Plus I am hoping maybe something has changed in 10 years. I am using Django 4.0.2, Python 3.8. Normal functionality - works fine Users sometimes upload content on the website (nothing sensitive). The website processes that content and emails back the results to the users Sometimes people will upload when they're not logged in. In that case, any values saved in the session are still accessible after the login (different behavior than the linked question above was experiencing). Everything works fine. New users - functionality gap - need ideas Sometimes visitors will upload content before creating an account After the upload, they're directed to create an account (which requires email verification, implemented through AllAuth) When they come back the session data is all lost Is there a way the website could recognize it's the same user post account creation / verification / login? Is setting a cookie my only option (if even that), or is there a more Django way of doing this using sessions? -
My model is not saving with in my database
VIEWS from django.shortcuts import render from django.views.generic import(ListView, CreateView) from models import UserProfileInfo from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from forms import UserForm # Create your views here. class UserCreateView(CreateView): template_name = "message_app/post_list.html" form_class = UserForm model = UserProfileInfo FORMS from django import forms from models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = UserProfileInfo fields = "__all__" POST_LIST.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>Please Sign Up</h1> <form method="post "> {{ form.as_p }} {% csrf_token %} <input type="submit" value="SignUp"> </form> <a href="{% url 'admin:index' %}">Admin</a> </body> </html> When I go inside my admin site I can't see an of this information saved Isn't the create class view already supposed to automatically save it or am I missing something -
Django form class and view class connected
Hi in my code(not written by me) i have django form class and views class. I dont know how this is connected each other. Can anyone tell me how this is connected? Also can any one please tell me how this messege : Credential is in use by {0} collections that are turned on and " "{1} collections that are turned off. Be mindful that over-using " "credentials may result in collecting being rate limited by the " "social media API is displayed, i mean if i need to change the alignment of this text where i should change? My code classes are : from forms.py : class CollectionTwitterSearch2Form(BaseCollectionForm): incremental = forms.BooleanField(initial=True, required=False, label=INCREMENTAL_LABEL, help_text=INCREMENTAL_HELP) def __init__(self, *args, **kwargs): super(CollectionTwitterSearch2Form, self).__init__(*args, **kwargs) self.helper.layout[0][5].extend(('incremental',)) if self.instance and self.instance.harvest_options: harvest_options = json.loads(self.instance.harvest_options) if "incremental" in harvest_options: self.fields['incremental'].initial = harvest_options["incremental"] def save(self, commit=True): m = super(CollectionTwitterSearch2Form, self).save(commit=False) m.harvest_type = Collection.TWITTER_SEARCH_2 harvest_options = { "incremental": self.cleaned_data["incremental"], } m.harvest_options = json.dumps(harvest_options, sort_keys=True) m.save() return m from views.py : def _get_credential_use_map(credentials, harvest_type): credential_use_map = {} if harvest_type in Collection.RATE_LIMITED_HARVEST_TYPES: for credential in credentials: active_collections = 0 inactive_collections = 0 for collection in credential.collections.all(): if collection.is_on: active_collections += 1 else: inactive_collections += 1 if active_collections == 0 … -
How do I resolve BulkwriteError when using MongoDb with djangorestframework-simplejwt?
I am using MongoDB and SimpleJWT in DjangoREST to authenticate and authorize users. I tried to implement user logout, whereby in SimpleJWT it's basically blacklisting a user token. When the first user logs in, everything seems okay and their refresh token is added to the Outstanding token table. But when I try to log in a second user, I get the below error: raise BulkWriteError(full_result) pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'jti_hex': 1}, 'keyValue': {'jti_hex': None}, 'errmsg': 'E11000 duplicate key error collection: fsm_database.token_blacklist_outstandingtoken index: token_blacklist_outstandingtoken_jti_hex_d9bdf6f7_uniq dup key: { jti_hex: null }', 'op': {'id': 19, 'user_id': 7, 'jti': '43bccc686fc648f5b60b22df3676b434', 'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY1OTY1NDUzNCwiaWF0IjoxNjU5NTY4MTM0LCJqdGkiOiI0M2JjY2M2ODZmYzY0OGY1YjYwYjIyZGYzNjc2YjQzNCIsInVzZXJfaWQiOjd9.aQmt5xAyncfpv_kDD2pF7iS98Hld98LhG6ng-rCW23M', 'created_at': datetime.datetime(2022, 8, 3, 23, 8, 54, 125539), 'expires_at': datetime.datetime(2022, 8, 4, 23, 8, 54), '_id': ObjectId('62eb00064621b38109bbae16')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 869, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: INSERT INTO "token_blacklist_outstandingtoken" ("user_id", "jti", "token", "created_at", "expires_at") VALUES (%(0)s, … -
TypeError at /dashboard/profiles/create/ path_and_rename() missing 2 required positional arguments: 'instance' and 'filename'
I am trying to save information from the form created out of the Django model. I am really not much experienced as this is my second project, Please help where you can. Thanks here is my view def profile_create_view(request): form = ProfileCreateForm(request.POST or None) if form.is_valid(): form.save form = ProfileCreateForm() context = { 'form':form } return render(request, 'users/profile', context) my form is here class ProfileCreateForm(forms.ModelForm): class Meta: model = Profile fields = [ 'avatar', 'user_type', 'first_name', 'last_name', 'gender', 'email', 'phonenumber', 'birth_date',] and then my model is here class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to = '', default = path_and_rename, blank=True) provider = 'provider' requester = 'requester' user_types = [ (provider, 'provider'), (requester, 'requester'), ] user_type = models.CharField(max_length=155, choices=user_types, default=requester) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') GENDER_MALE = 'Male' GENDER_FEMALE = 'Female' OTHER = 'Other' GENDER_CHOICES = [ (GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female'), (OTHER, 'Other'), ] gender = models.CharField(max_length=15, choices=GENDER_CHOICES, blank=True) email = models.EmailField(default='none@email.com') phonenumber = models.CharField(max_length=15, default='') birth_date = models.DateField(default='1975-12-12') Thank you -
403 Forbidden with Django Permission error
I cannot seem to have a user create a post without having a 403 error display after creating an account, would anyone be willing to take a look at the code and see if they can tell me why I the user is not automatically placed into the default group when creating account from django.shortcuts import render, redirect from .forms import RegisterForm, PostForm from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User, Group from .models import Post @login_required(login_url="/login") def home(request): posts = Post.objects.all() if request.method == "POST": post_id = request.POST.get("post-id") user_id = request.POST.get("user-id") if post_id: post = Post.objects.filter(id=post_id).first() if post and (post.author == request.user or request.user.has_perm("main.delete_post")): post.delete() elif user_id: user = User.objects.filter(id=user_id).first() if user and request.user.is_staff: try: group = Group.objects.get(name='default') group.user_set.add(user) group.user_set.remove(user) except: pass try: group = Group.objects.get(name='mod') group.user_set.remove(user) except: pass return render(request, 'main/home.html', {"posts": posts}) @login_required(login_url="/login") @permission_required("main.add_post", login_url="/login", raise_exception=True) def create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect("/home") else: form = PostForm() return render(request, 'main/create_post.html', {"form": form}) def sign_up(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('/home') else: form = RegisterForm() return render(request, 'registration/sign_up.html', … -
Django UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 5: invalid continuation byte
for the first time I am asking for help because I have not seen such a problem before, I rummaged through Google and did not find an answer, although other people had similar situations, but their solutions did not fit( Username in english path too ) Problem: first django project, manage.py runserver have error. Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 04, 2022 - 01:06:46 Django version 4.1, using settings 'base.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\pthn\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\pthn\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\pthn\lib\site-packages\django\utils\autoreload.py", line 64, in wrapp er fn(*args, **kwargs) File "C:\pthn\lib\site-packages\django\core\management\commands\runserver.py", line 158, in inner_run run( File "C:\pthn\lib\site-packages\django\core\servers\basehttp.py", line 236, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\pthn\lib\site-packages\django\core\servers\basehttp.py", line 76, in __init__ super().__init__(*args, **kwargs) File "C:\pthn\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\pthn\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\pthn\lib\http\server.py", line 140, in server_bind self.server_name = socket.getfqdn(host) File "C:\pthn\lib\socket.py", line 756, … -
Django app fails to load in iframe despite using CSP_FRAME_ANCESTORS
I'm looking to load a Django site of my design into an iframe. For this, I added the following lines in my Django settings.py file: MIDDLEWARE = [ ... 'csp.middleware.CSPMiddleware', ... ] . . . CSP_FRAME_ANCESTORS = ("'self'", 'localhost:*') So that I can load my site from any address of my localhost. However, when I load my site at the following url:http://localhost:3000/searchEngine I get in the devtools inspector the following error: Refused to frame 'https://gkwhelps.herokuapp.com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self' localhost:*". I tried to find the solution on this stack overflow question, on this blog, also on another blog on the internet and again on this blog and tried to replace CSP_FRAME_ANCESTORS by CSP_FRAME_SRC like this: CSP_FRAME_SRC = ["'self'", 'localhost:*'] #instead of CSP_FRAME_ANCESTORS = ("'self'", 'localhost:*') but that didn't solve the problem and the header was even ignored. Still, I would like to be able to load my site in an iframe from any port on my localhost. -
How create table (with values) in database from .sql or .txt file which I will take from user via django website
I have a form with input tag type=field, What I want is when user upload .txt or .sql file. My django view read that file and execute whole file in my already connected database, and create all tables and values which user's file have. I tried few things but I am facing errors like I read file like this var2 = request.FILES['myfile'].read().splitlines() But when I print var2 I notice that there are many single quotes ('), \r, \s, \n, \t in var2. Can any pro guy guide me what to do? Thank You In Advance. -
Forbidden (CSRF token missing.): /ckeditorupload/ in django?
When i try to upload an image in the admin panel of django, i get this Forbidden (CSRF token missing.): /ckeditorupload/ i have this result in my console. here my model from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) #content = RichTextField(blank=True, null=True) image = RichTextUploadingField() #image = models.ImageField(upload_to='featured_image/%Y/%m/%d/') # created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title my views from django.views import generic from .models import Post from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt @method_decorator(csrf_exempt, name='dispatch') class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' I tried to exempt the CSRF but i get same issues, & when i delete the middlewareCsrf it's dont works too, since i'm using the admin django and not a custom post method, i dont know where to pass the {{ csrf_token }} Thanks for your help :) -
Trying to Debug Python Django application with VS Code remote-containers not running
I've been using the remote-containers in VS Code to run a Python Django application successfully for a couple of months, as I have an M1 machine and it's just a nightmare trying to install all the dependencies locally, and it was working really well. I came back to the application yesterday and now it's suddenly not working, the container seems to build without any issues and I can see it's running, and the build logs don't present any errors. But when I try and run with or without debugging the it pops up the run tool bar (start, stop, step ect) for a second and then stops with no output or errors at all. Has anyone seen this before? or have any ideas how to try and get it running again? Using the rebuild container and rebuild container without cache commands both seem to run without errors I updated both VS Code and Docker to the latest version I tried cloning the repository again I verified that the docker image builds locally without issue The vs code remote containers plugin seems to still be working because I tried it with a Flask application example I used before to demo the … -
My Django App works on my local development server but does not work on my Linode VPS
I have the exact same code deployed locally on development server and Linode Virtual Private Server. The Local site works fine, but when I try to access the same url on the VPS, I see this in the browser: This site can’t be reached XXX.XXX.XXX.X refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED Even when I go to the admin site it is broken. I have narrowed the change down to my views.py and settings.py file changes, as I was making one code change at a time to try and find out where the VPS did not like my code. I am unable to understand why the Django App just seems to break. My views.py function, the last line of code will be called: def start_or_end_fast(request): if request.method == 'POST' and 'start_fast' in request.POST: start() return HttpResponseRedirect(reverse('start_or_end_fast')) elif request.method == 'POST' and 'end_fast' in request.POST: print('mmmmm') end() return HttpResponseRedirect(reverse('start_or_end_fast')) elif request.method == 'POST' and 'duration' in request.POST: duration = time_difference() return render(request,'startandstoptimes/index.html', {'duration': duration}) else: return render(request,'startandstoptimes/index.html') settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # Quick-start development … -
Django Management Command For Exporting Model data
I am trying th create a management command to export model data in csv but it is not working can anyone help me to export the data to the csv. just two field name i added to export that data to csv . import csv from appdirs import unicode from django.core.management.base import BaseCommand def _write_csv(meta): f = open(meta['file'], 'w+') writer = csv.writer(f, encoding='utf-8') writer.writerow( meta['fields'] ) for obj in meta['class'].objects.all(): row = [unicode(getattr(obj, field)) for field in meta['fields']] writer.writerow(row) f.close() print ('Data written to %s' % meta['file']) def your_model(): from new_db.models import Product meta = { 'file': '/tmp/your_model.csv', 'class': Product, 'fields': ('name','id') } _write_csv(meta) class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write("Product Moved To CSV.") -
is using multitable inheritance that bad in django and shoud i use it for my case?
basically, I have the following models for products: class Category(models.Model): name = models.charfield() class Product(models.Model): ....... class PhyscialProduct(Product): category = models.ForeignKey(Category) ......... class Course(Product): ......... class Book(Product): ......... I had to do it like this because each product has its own fields, but I was reading how multi-table inheritance "that it's evil", and because mostly going to work with the subclasses of the Product class, should I use content type and generic foreign key instead, or using multi-table inheritance is not that bad? -
How to access many-to-many field associated with specific model id in Django?
For a specific project id, I would like to be able to access all users associated with the project. models.py is below: class IndividualProject(models.Model): project = models.CharField( max_length = 64 ) group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name = "project_group", blank=True, null=True, ) user = models.ManyToManyField( UserProfile, blank = True, ) def __str__(self): return f"Project {self.project}" If I do IndividualProject.objects.get(id = 1), I would like to be able to see all of the users associated with that project. I can find all projects associated with a specific user per the below: test = UserProfile.objects.get(id = 1) test.individualproject_set.all() Is there a way to do the above but using a specific project? Thank you! -
Django 4.0.1 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. when I run make migrations
I changed something in the Request model and tried running makemigrations and it is giving me this error $python manage.py makemigrations Traceback (most recent call last): File "/Users/raymond/Documents/GitHub/Management/manage.py", line 22, in <module> main() File "/Users/raymond/Documents/GitHub/Management/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/apps/config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/raymond/Documents/GitHub/Management/request/models.py", line 7, in <module> class Request(models.Model): File "/Users/raymond/Documents/GitHub/Management/request/models.py", line 9, in Request teacher = models.ForeignKey(User, on_delete=models.CASCADE, choices=[(u.username, u) for u in User.objects.filter(profile__teacher_status=True)], related_name='teacher') File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/query.py", line 974, in filter return self._filter_or_exclude(False, args, kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/query.py", line 992, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/query.py", line 999, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1375, in add_q clause, _ = …