Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotate abstract Django Model instance type
Let's say I have two Django models: class MyModel1(models.Model): class Meta: abstract = True @classmethod def foo(cls, name): pass class MyModel2(models.Model): model1: MyModel1 = models.ForeignKey("MyModel1") First model is abstract, so I have to refer to it lazily. Now if I try to access mymodel2.model1. Pylance will suggest foo as an option. What is the correct way to assign model1 field to be an instance, not the class itself? -
Django connects Signal, but App not in INSTALLED_APPS
I have two Django apps, foo and bar, which are both listed in the INSTALLED_APPS setting. foo sends a Signal which is received by bar. I want to test foo. So, I want to isolate it, i.e., bar should not listen to the signal. Usually, bar connects to the signal using the AppConfig.ready() method: class BarConfig(AppConfig): def ready(self): from foo.signals import foo_signal from .signals import handle_foo_signal foo_signal.connect(handle_foo_signal) In the test code, I remove bar from the INSTALLED_APPS setting, using the @modify_settings() decorator: @modify_settings(INSTALLED_APPS=dict(remove=["bar"])) def test_foo(self): ...test code... I would expect, that bar would not listen to the signal. However, it does. I know, that I could disconnect each Signal. But I'm looking for a way to temporary "remove" an app entirely. Is there a way to isolate apps and their Signal receivers easily? I debugged the code and found out, that the bar app is still in INSTALLED_APPS when ready() is called. I expected, that the app config is not called at all. -
Iterate through Django models fields with for loop
I have a model in Django named models_bdc models.py class models_bdc(models.Model): id_bdc = models.CharField(primary_key=True, max_length=50) bdc_index_line_1 = models.CharField(max_length=50) bdc_quantity_1 = models.CharField(max_length=20) bdc_description_1 = models.CharField(max_length=50) bdc_index_line_2 = models.CharField(max_length=50) bdc_quantity_2 = models.CharField(max_length=100) bdc_description_2 = models.CharField(max_length=100) bdc_index_line_3 = models.CharField(max_length=50) bdc_quantity_3 = models.CharField(max_length=100) bdc_description_3 = models.CharField(max_length=100) In my view I would like to iterate through the fields with a for loop and replace the digit by the i counter value I would look like something like : views.py queryset = models_bdc.objects.filter(id_bdc=1) [...] for i in range(3): models_bdc.bdc_index_line_ + i models_bdc.bdc_quantity_ + i models.bdc.bdc_description_ + i But it's not working. Is there a way to do this ? Thanks -
Ensure Sequential Task Execution with Celery in Django REST Framework?
I have a Django REST Framework project where I need to call two Celery tasks sequentially. Specifically, I need to call first_function and then after some operations, call the second_function, ensuring that second_function runs only after first_function has completed. # tasks.py from celery import shared_task @shared_task def first_function(): # Logic for the first function @shared_task def second_function(): # Logic for the second function This is my view.py first_function.delay() # some codes .... # now i need to call my second_function.delay() chain(first_function.s(), second_function.s()).delay() My concerns are: If multiple requests are made to the view simultaneously, will second_function correctly wait for the corresponding first_function to complete? I'm a little confused, How can I ensure that second_function runs after the specific first_function related to the same request?(Note: I can't add sleep or any blocking code in the middle of my code.) Any guidance or best practices for handling this scenario with Celery would be greatly appreciated! -
error shows when using libreoffice to convert docx file to pdf
I upload docx file in html form then I want to convert this file to pdf in ubuntu server but it shows error like CalledProcessError at /add-document Command '['libreoffice', '--headless', '--convert-to', 'pdf', '/var/www/html/dev/media/documents/Lavender_Bay_Boatshed_Website_Testing_61gWm6r.docx', '--outdir', '/var/www/html/dev/media/documents/Lavender Bay Boatshed Website Testing.pdf']' returned non-zero exit status 77. @login_required def add_document(request): title = "Add document" if request.method == 'POST': file = request.FILES.get('file') check = request.POST.get('check') subject = request.POST.get('subject') message = request.POST.get('message') print(request.POST) names = [] emails = [] for key in request.POST: if key.startswith('email_'): emails.append(request.POST[key]) elif key.startswith('name_'): names.append(request.POST[key]) print(emails) print(names) recipients = [] list_of_dicts = [{'email': email, 'name': name} for email, name in zip(emails, names)] if file: if (file.name.endswith('.jpg')) or (file.name.endswith('.png')): obj = Documents(document=file,name=file.name,user=request.user) obj.save() image = Image.open(obj.document.path) iml = image.convert('RGB') folder = r'C:\Users\admin\Desktop\projects\Document-sign\media\documents' path = os.path.join(folder, file.name.split('.')[0] + '.pdf') os.remove(obj.document.path) iml.save(path) obj.document = f"documents/{file.name.split('.')[0]}.pdf" obj.save() os.remove(obj.document.path) if check: request.session['check'] = False return redirect('sign_document') else: recipients.append({'emails':list_of_dicts,'subject':subject,'message':message}) request.session['recipients'] = recipients request.session['check'] = True return redirect('make_envelope') elif file.name.endswith('.docx'): obj = Documents(document=file, name=file.name, user=request.user) obj.save() # Define paths path = os.path.join(settings.MEDIA_ROOT, 'documents') input_path = obj.document.path # Run LibreOffice conversion try: result = subprocess.run( ['libreoffice', '--headless', '--convert-to', 'pdf', input_path, '--outdir', path], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) print(result.stdout) print(result.stderr) except subprocess.CalledProcessError as e: print("Error occurred:", e.stderr) raise # Remove the … -
Playwright: Missing Dependencies for Running Browsers on AWS EC2 (Ubuntu)
I'm trying to use Playwright in a Python project to automate browser actions. The setup works perfectly on my local machine, but I encounter issues with missing system dependencies when deploying the project on an AWS EC2 instance. Environment: AWS EC2 Instance: Ubuntu 20.04 Python: 3.12 Playwright Version: 1.45.1 Steps Taken: Installed Playwright: pip install playwright Installed Playwright browsers: python -m playwright install Tried installing system dependencies: sudo npx playwright install-deps Error Messages: I still receive the following error message when trying to run Playwright on the AWS EC2 instance: "BrowserType.launch: Executable doesn't exist at /root/.cache/ms-playwright/webkit-2035/pw_run.sh\n╔════════════════════════════════════════════════════════════╗\n║ Looks like Playwright was just installed or updated. ║\n║ Please run the following command to download new browsers: ║\n║ ║\n║ playwright install ║\n║ ║\n║ <3 Playwright Team ║\n╚════════════════════════════════════════════════════════════╝" Here is the screenshot of the error: Error on Postman Code Snippet: import asyncio import re import logging import time from playwright.async_api import async_playwright async with async_playwright() as p: browser = await p.webkit.launch(headless=True) for attempt in range(retries): try: context = await browser.new_context(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3") page = await context.new_page() for nav_attempt in range(retries): try: await page.goto(url, timeout=30000) # Reduced timeout for faster retries logger.info(f"Navigated to {url}") break except … -
Weasyprint dependency 'gobject-2.0-0' installation error on Railway.app
I am using this dockerfile configuration for my django project FROM python:3.12.2-slim-bullseye Install system dependencies RUN apt-get update && apt-get install -y \ python3-pip \ python3-cffi \ python3-brotli \ libpango1.0-0 \ libpangoft2-1.0-0 \ libharfbuzz-subset0 \ libffi-dev \ libcairo2 \ libcairo2-dev \ libjpeg62-turbo-dev \ libgdk-pixbuf2.0-0 \ libgdk-pixbuf2.0-dev \ libgobject-2.0-0 \ libgobject2.0-dev \ build-essential \ && apt-get clean ENV LD_LIBRARY_PATH=/usr/lib:/usr/local/lib:/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH Set the working directory WORKDIR /PAQSBackend Copy the application code COPY . /PAQSBackend/ RUN pip install -r requirements.txt COPY PAQSBackend.wsgi /PAQSBackend/PAQSBackend.wsgi CMD ["gunicorn", "--bind", "0.0.0.0:8000", "PAQSBackend.wsgi"] The build and deployment runs fine. However, when I run the project, I get this error message File "/opt/venv/lib/python3.11/site-packages/cffi/api.py", line 827, in loadbackend_lib raise OSError(msg) OSError: cannot load library 'gobject-2.0-0': gobject-2.0-0: cannot open shared object file: No such file or directory. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0' I would want to know what is actually happening and also how to resolve this. I only face this issue when I am deploying it on Railway.app -
Django Axes Lockout Not Working as Expected
I’m using Django Axes to lock out users after a certain number of failed login attempts. However, despite my configurations, users are still able to log in immediately after being locked out if they enter the correct credentials. I want to ensure that users are locked out for 1 hour, regardless of whether they enter the correct credentials during that period. Here are my current settings in settings.py: from datetime import timedelta AXES_FAILURE_LIMIT = 3 AXES_LOCK_OUT_AT_FAILURE = True AXES_COOLOFF_TIME = timedelta(hours=1) # Set cool-off time to 1 hour AXES_LOCKOUT_CALLABLE = "customer_manager.views.lockout" AXES_RESET_ON_SUCCESS = False AXES_ENABLE_ACCESS_FAILURE_LOG = True AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT = False AXES_SENSITIVE_PARAMETERS = [] AXES_LOCKOUT_PARAMETERS = ["username"] AXES_CACHE = 'default' CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } I have verified the following: axes.middleware.AxesMiddleware is included in the MIDDLEWARE settings, placed after AuthenticationMiddleware. I have run python manage.py migrate and confirmed there are no pending migrations. I have temporarily removed the custom lockout callable to test with default settings. Despite these configurations, users are still able to log in immediately after being locked out if they enter the correct credentials. Here are some relevant log entries: AXES: User login failed, running database handler … -
why when i start a subprocess in python using get request starts only at the second time
i have a button that create a database inside settings.py and add it to mysql DB . The button sends a get request to api endpoint. The problem is when i click the button the response get back with 500 response status code, when i click the second time it passes and create the DB and return 200 ok you can see more details as the screen shots below i added in settings.py: ALLOWED_HOSTS = ['django','localhost','127.0.0.1'] (django is a name inside nginx conf file) this is my middleware: MIDDLEWARE = [ "MyApp.middleware.ServerCheckMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", . . ] The file execution responsible for the adding of DB is ran inside a views file: class ActivateTheUser(APIView): def get(self, request, email): cloneresult = subprocess.run( [sys.executable, clone_db_script_path, '--host', _host, '--user', _user, '-- password', _password, '--database', _dbname ], capture_output=True, text=True ) -
Deploy multipe Django, Celery & Redis App in one VPS
I am planning to deploy multiple applications(approx 100+) in single VPS. Each Django app will have it's own celery and redis app. How should I deploy all these applications properly? I have tried to create individual service for each application but it became impossible to create a new service each time I'm deploying a new application. -
Django celery task manager
please sugest me a open-source web GUI (except " FLOWER ") to manage my Django applications celery tasks (like :- view , delete , restart , flush ) using redis as a message broker . I already tried apache airflow for the same but , unable to integrate celery tasks with it . if any documentation for the same please share it . -
About machine learning to identify plant growth cycles
I want to train a simple one that can identify the growth cycle of plants in pictures, such as seedling stage or mature stage. I tried to find some data sets, but I didn't figure out how to implement it. Please tell me if you have any good ideas or if you have the ability, I will give you a certain reward cais201219@gmail.com -
ModuleNotFoundError: No module named '—'
Am attempting to deploy a Django app on Digital Ocean's Droplet. I have gunicorn, nginx, postgresql and my domain ip connected. However, am unable to load the site when I visit the domain. Running - sudo tail -f /var/log/gunicorn_supervisor.log (venv) root@pmkattorneys-droplet:/var/www/pmkattorneys# sudo tail -f /var/log/gunicorn_supervisor.log return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked ModuleNotFoundError: No module named '—' [2024-08-07 07:50:23 +0000] [396636] [INFO] Worker exiting (pid: 396636) [2024-08-07 07:50:23 +0000] [396635] [ERROR] Worker (pid:396636) exited with code 3 [2024-08-07 07:50:23 +0000] [396635] [ERROR] Shutting down: Master [2024-08-07 07:50:23 +0000] [396635] [ERROR] Reason: Worker failed to boot. nginx error 2024/08/07 07:50:53 [crit] 381423#381423: *355 connect() to unix:/var/www/pmkattorneys/web.sock failed (2: No such file or directory) while connecting to upstream, client: 194.28.224.213, server: pmkattorneys.com, request: "GET /.env HTTP/1.1", upstream: "http://unix:/var/www/pmkattorneys/web.sock:/.env", host: "104.131.178.60" Anyone else has expereienced this ? Your help is highly appreciated I tried downgrading my oython ftom 3.12 to 3.6 and back to 3.12. Deleted the virtual env and recreated it. -
CORS header on OPTIONS request?
I am trying to set up a webapp with Angular and Django but I have a problem with the CORS headers. As far as I understand, in order to include cookie data from the frontend in the request (such as csrf token and session id), I need to set the withCredentials to true in the request. So a GET request looks like this.http.get(this.url, { withCredentials: true });. Then the browser says Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at xxx. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’). I can fix this for the GET request by adding the header to the response with response["Access-Control-Allow-Credentials"] = "true", but the problem comes when I make a POST request. In this case the frontend automatically sends an OPTIONS request before the POST, which as far as I understand is standard and is used to check what the backend allows to be posted. However, I can't set the CORS header for the response of the OPTIONS request, so in effect I can't send a POST request. Is there a way to set the header for OPTIONS responses or am I doing something wrong in general? -
Issue with sending JSON Array in multipart/form-data from POSTMAN
I've been struggling with writable serialises in DRF and I keep having this issue: "music_preferences": [ "Incorrect type. Expected pk value, received list." ], "artists": [ "Incorrect type. Expected pk value, received list." ] I'm building an endpoint that is supposed to allow an admin to create an event. This is the serializer: class EventCreateSerializer(serializers.ModelSerializer): music_preferences = serializers.PrimaryKeyRelatedField(queryset=Music.objects.all(), many=True, write_only=True) artists = serializers.PrimaryKeyRelatedField(queryset=Artist.objects.all(), many=True, write_only=True) event_picture = serializers.ImageField(required=False) # Made optional class Meta: model = Event fields = ( 'name', 'start_date', 'end_date', 'venue', 'minimum_age', 'vibe', 'public_type', 'dresscode', 'music_preferences', 'event_picture', 'artists', ) def create(self, validated_data): music_preferences_data = validated_data.pop('music_preferences') artists = validated_data.pop('artists') # Check if event_picture is provided, else use the venue's image if 'event_picture' not in validated_data or not validated_data['event_picture']: venue = validated_data['venue'] validated_data['event_picture'] = venue.venue_picture # Use venue_picture from the venue event = Event.objects.create(**validated_data) # Set music preferences event.music_preferences.set(music_preferences_data) event.artists.set(artists) return event This is the view in which it is invoked: def post(self, request, venue_id): data = request.data.copy() # Add files to the data dictionary if 'event_picture' in request.FILES: data["event_picture"] = request.FILES["event_picture"] data['music_preferences'] = json.loads(data['music_preferences']) data['artists'] = json.loads(data['artists']) serializer = EventCreateSerializer(data=data) if serializer.is_valid(): event = serializer.save() event_data = EventCreateSerializer(event).data event_data['id'] = return Response({ 'data': event_data }, status=status.HTTP_201_CREATED) # Log serializer … -
Showing django static images on emails
I am trying to send an email with django static images on my emails like using {% static "path_to_img" %}, but that's not working. Then I tried giving the image it's full path by giving the url and the domain in my view, but that's not working either. My mail.html: <!DOCTYPE html> {% load static %} <html> <head> <title>Order Rejected</title> </head> <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; color: #333; background-color: #f5f5f5;"> <div style="background-color: white; padding: 20px; border: 1px solid #ddd;"> <header style="margin-bottom: 20px;"> <img src="{{ request.build_absolute_uri }}{% static 'event/images/logo.svg' %}" alt="img" style="height: 30px;"> </header> <div style="text-align: center; margin-bottom: 20px;"> <img src="{{ request.build_absolute_uri }}{% static 'event/images/order_rejected.png' %}" alt="Order Status" style="width: 80%; max-width: 400px;"> </div> <h1 style="font-size: 24px; margin-bottom: 5px;">Order Rejected</h1> <p style="margin-bottom: 20px;">Order number: #{{ order.ref_code }}</p> <p style="margin-bottom: 20px;">Hi {{ order.user.first_name }},<br> We regret to inform you that your order has been rejected. The full amount has been refunded to your original payment method. If you have any questions, please email us at info@everyeventaus.com.au.</p> <a href="#" style="display: block; background-color: #8B0000; color: white; text-align: center; padding: 10px; text-decoration: none; margin-bottom: 20px;">Log into account</a> <div style="background-color: #333; color: white; padding: 10px; margin-bottom: 10px;"> <h2 style="margin: 0; font-size: … -
Restrict IP access to the Django admin deployed on Render app
Good day, community. I am developing a Django application for an online store, where the seller will publish their products through the admin panel, and customers will see the products through views and templates. While I was developing locally, there was no problem accessing the admin panel since I was running it from my PC. However, now that I have deployed the application on Render app, I've just realized that I can access the admin panel by appending 'admin/' to the URL. How can I restrict access to the admin panel to certain IPs, like a firewall, meaning only my IP can access the admin panel? Please help me I have the starter plan -
Django - Assigning employee to projects on various dates (durations)
How can I assign each employee (many) on projects (many) while also tracking the dates when they were assigned and removed from each project? I realize this is a ManyToManyField type of relationship in Django where: class Project(models.Model): projectname=models.CharField() class Employee(models.Model): firstname = models.CharField() lastname = models.CharField() start_date = models.DateField(null=False) end_date = models.DateField(null=True) #because we don't know this all the time projects = models.ManyToManyField(Project) But I hope to be able to generate an app where I can both view each employee where they are on projects currently and where they've been in the past. The tricky part here consists in me possibly sending employees back to the same project after having taken them off for a couple of weeks to perform on another project. Please forgive me for this is my first post/question on this site and haven't quite grasped the proper format for asking questions. I simply tried adding a start_date and an end_date for each employee but I do not think that is working properly as I have a feeling those dates are overwritten every time I modify Employee. I am missing something and hope to find others more experienced that would see the easy solution here. -
A more elegant approach to writing Django’s unit tests
I am currently writing tests using Django’s unit tests (based on Python standard library module: unittest). I have written this test for my Contact model which passes: class ContactTestCase(TestCase): def setUp(self): """Create model objects.""" Contact.objects.create( name='Jane Doe', email='janedoe@gmail.com', phone='+2348123940567', subject='Sample Subject', message='This is my test message for Contact object.' ) def test_user_can_compose_message(self): """ Test whether a user can compose a messsage in the contact form.""" test_user = Contact.objects.get(name='Jane Doe') self.assertEqual(test_user.email, 'janedoe@gmail.com') self.assertEqual(test_user.phone, '+2348123940567') self.assertEqual(test_user.subject, 'Sample Subject') self.assertEqual(test_user.message, 'This is my test message for Contact object.') Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.005s OK Destroying test database for alias 'default'... However, I had to use the assertEqual method 4 times in this test (could be more when testing models with more fields). It seems like this doesn't follow the DRY principle. I know from the docs that assertEqual(first, second, msg=None) tests that first and second are equal. If the values do not compare equal, the test will fail. Is there a workaround or a more elegant approach to writing such tests? -
Make list of list populated by Django or MYSQL query filtered by column's name
I'm not very good in Django or Mysql so please be tolerant, I have this table in my DB named table_bdc (Simplified version) I would like to iterate through the DB to create a list of list with a query depending on the column's name last digit (_1 or _2 or _3 and so on). Something like : final_list = [] for i in range(2) result = models_bdc.objects.raw("SELECT * FROM table_bdc WHERE id='1' AND column name ends with RLIKE %s",["_"+(i+1)]) final_list.append(result) For example with the first line (id 1), the expected result would be : final_list = [[3,4],[6,7]] I already searched the forum to learn and get to this point but the rest is still too complex for me yet ... Can someone please show me how to do this ? PS: The DB cannot be refactored or changed I have to deal with it this way. Thanks -
Typescript output directory setup
I need help to setup my tsconfig.json file. I'm building a Django project with multiple apps, the base structure for what I would like to obtain is as follow: project/ |-app1/ | |-app2/ | |-tsconfig.js Now, each app folder should have this structure: appX/ |-static/ |-appX |-js/ | |-test.js | |-ts/ |-test.ts Basically I want my tsconfig to output the relative js file always inside "../js/", and this has to be true for any app of the project. Is this possible to achieve? I have tried to change outDir but I can't build it so that it takes into consideration a generic relative path. For example, using ../js simply creates the javascript files inside in a folder on the same level as "project" -
Python Django, using external MSSQL database
I'm trying to make a django website that connects to an external MSSQL database to retrieve information only (read-only). This database is huge with hundreds of tables. I can currently get it to work by creating a function in my django app that uses the connectionString and runs a raw SQL query and returns it in a pandas dataframe. Somehow I feel this is not how Django should be used. Can you please guide me on how to do this in the proper Django way. I think I need to use models? but this is an external database and I don't want to write anything to it. I also don't want to have to define all the table names in my models, but I will if I have to. Can you please guide me on how to go about this while making sure the database stays as read-only? How do I structure my settings.py,How do I structure my models.py,How do I structure my views.py to be able to interact with the db? import pyodbc import pandas as pd def SQL_to_df(driver,server,database,user,password,query): connectionString = pyodbc.connect(f"Driver={driver};Server{server};Database={database};UID={user};PWD={password};") df = pd.read_sql(query, connectionString) return df -
If statement django template correct construction
Could someone help me to find the correct way to construct the template in django. If the view object is edited by moderator (user is not owner) I put into context an object that has permissions as attributes. For example, object.permission_profile is boolean field that allows to edit user-owner profile. So, in template I suggest I need to use if-statement to put necessary url, one url - when both object exists and permission is True, and another url - if object is not in context. I put into template if-statement such way {% if object %} {% if object.permission %} url-1 {% endif %} {% else %} url-2 {% endif %} Is this correct way? Or is there another right or faster rule to use it? Thank you! -
How to optimize method with multiple query calls?
I have an event system in my app. Every time a user deletes/updates/creates and object a new event is created in the database with the info of the object and the type of event it is. My Event model looks something like this: class Event(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) model = models.CharField(max_length=200) object_id = models.IntegerField() event_type = enum.EnumField(ModelEventType) In this model, model is the name of the object's model, and object_id is the ID of that object. My app also has multiple access permissions: some objects are private to the user, while others are shared among teammates. Thus, I need to restrict events to only those that correspond to a user's access level. To fetch each user's events, I retrieve all objects the user has access to, obtain their IDs, and then fetch the events related to those objects. I use a method like this to fetch the objects belonging to a user: class Event(models.Model): .... @staticmethod def get_events_ids(request): object_ids = {} Object1 = apps.get_model("myapp", "Object1") Object2 = apps.get_model("myapp", "Object2") Object3 = apps.get_model("myapp", "Object3") Object4 = apps.get_model("myapp", "Object4") Object5 = apps.get_model("myapp", "Object5") objects1 = Object1.objects.filter(...) objects2 = Object2.objects.filter(...) objects3 = Object3.objects.filter(...) objects4 = Object4.objects.filter(...) objects5 = Object5.objects.filter(...) objects = … -
TypeError: ForeignKey(None) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
I am not new to Django but I am to Apache. I recently developed a web app and tested its deployment on Nginx and it worked just fine. The client has a preference for Apache though and I created a config file. After this, I am getting a 500 server error and the error above is presenting itself. Below is part of the traceback in the Apache error log: [Tue Aug 06 19:48:10.945075 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "<frozen importlib._bootstrap>", line 688, in _load_unlocked [Tue Aug 06 19:48:10.945077 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "<frozen importlib._bootstrap_external>", line 883, in exec_module [Tue Aug 06 19:48:10.945079 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed [Tue Aug 06 19:48:10.945082 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "/var/www/mysite/vir/lib/python3.10/site-packages/django/contrib/admin/models.py", line 48, in <module> [Tue Aug 06 19:48:10.945086 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] class LogEntry(models.Model): [Tue Aug 06 19:48:10.945089 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "/var/www/mysite/vir/lib/python3.10/site-packages/django/contrib/admin/models.py", line 54, in LogEntry [Tue Aug 06 19:48:10.945090 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] user = models.ForeignKey( [Tue Aug 06 19:48:10.945092 2024] [wsgi:error] [pid 344644] [remote 169.255.52.63:23675] File "/var/www/mysite/vir/lib/python3.10/site-packages/django/db/models/fields/related.py", line 959, in __init__ [Tue Aug 06 19:48:10.945094 2024] [wsgi:error] [pid …