Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Troubleshooting Increasing Memory Usage in a Django Application Deployed on AWS
We've successfully built a web application employing React for the frontend and Django, coupled with the Django Rest Framework (DRF), for the backend. The backend component has been deployed on Amazon Web Services (AWS) via the EC2 and ECS services. Currently, I'm observing a steady rise in memory usage for my container, as evidenced by the below graph. The dips you see in the graph correspond to application deployments. For managing our HTTP server, we're utilizing Gunicorn. The command used as an entry point is as follows: gunicorn booking_system.wsgi:application --bind 0.0.0.0:8000 --workers=$workers --max-requests 100 --max-requests-jitter 25 This command is intended to avert memory leaks by restarting the Gunicorn worker after a certain number of requests. I would appreciate any advice you can offer. What diagnostic measures can I take to discern the reason behind the escalating memory usage? Adding these options --workers=$workers --max-requests 100 --max-requests-jitter 25 I would expect to maintain a regular memory consumption. -
Django template cannot be found
I'm trying to render a template using django but keep getting an error saying that the template could not be found even though I have made a template folder with the html file in it. I am following this tutorial. This is the error I get: Internal Server Error: /playground/hello/ Traceback (most recent call last): File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/shavakvasania/Desktop/compia/playground/views.py", line 5, in say_hello return render(request, 'hello.html') File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/shavakvasania/.local/share/virtualenvs/compia-kMxYXwId/lib/python3.10/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: hello.html the issue is likely just that the interpreter can't find the correct templates folder but not sure how to fix. I added the application to settings.py.(https://i.stack.imgur.com/cv6XO.png) Created all the urls in the main urls and in the playground app urls. Here are my template settings in case something is wrong there but I just followed what the tutorial said to do: -
compatibility between django version of 1.11.23 and postgres version of 13.8
My application uses django version of 1.11.23. I am thinking of switching the postgres version to 13.8, currently I m using 12.7 of postgres version. May I know if anyone faced compatibility issues while connecting django version 1.11.23 to 13.8 version of postgres -
Filtering from a pivot table on Django Rest Framework returns all the values
I have a project in Django using Django Rest Framework with this models. job.py from django.db import models from .base import BaseModel class Job(BaseModel): title = models.CharField(max_length=100) races = models.ManyToManyField('Race', through='JobRace') skills = models.ManyToManyField('Skill') def __str__(self): return f"{self.title}" race.py from django.db import models from .base import BaseModel class Race(BaseModel): name = models.CharField(max_length=100) ... image = models.ImageField(default=None) description= models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.name} and jobRace.py who is the pivot table between jobs a races, I specified instead of letting Django auto generate it because I wanted to add an aditional image field to the pivot table from django.db import models from rpg.models.job import Job from rpg.models.race import Race from .base import BaseModel class JobRace(BaseModel): job = models.ForeignKey(Job, related_name='job_race', on_delete=models.CASCADE) race = models.ForeignKey(Race, related_name='job_race', on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, upload_to='jobs/') def __str__(self): return f"{self.job.title} - {self.race.name}" with their serializers job.py from rest_framework import serializers from ..models.job import Job from .skill import SkillSerializer from .jobRace import JobRaceSerializer class JobSerializer(serializers.ModelSerializer): job_race = JobRaceSerializer(many=True,read_only=True) class Meta: model = Job fields = '__all__' race.py from rest_framework import serializers from ..models.race import Race class RaceSerializer(serializers.ModelSerializer): class Meta: model = Race fields = '__all__' jobRace.py from rest_framework import serializers from ..models.jobRace import … -
Django Proxy model fields
i am using values(*self.feilds) on my queryset to get data from fields. But it doesn't work for me because I need to use proxy model's fields and using the values(*self.feilds) on them returns me FieldError: Cannot resolve keyword 'current_account' into field. i want to get values from normal fields along with proxy model fields. How can I implement it? models.py: class CreditsTrancheProxy(ReportMixinn, CreditsTranche): class Meta: proxy = True objects = CreditsTrancheProxyManager() def get_data_current_account(self): try: credit_account = self.credit.creditaccount_set.get( type_id=3, credit=self.credit, tranche=self.tranche) return {'КП': f'{credit_account.account.current_balance}'} except ObjectDoesNotExist: return {'error': ''} current_account = property(get_data_current_account) def get_data_percent_account(self): try: percent_account = self.credit.creditaccount_set.get( type_id=2, credit=self.credit, tranche=self.tranche) return {'Остаток %': f'{percent_account.account.current_balance}'} except ObjectDoesNotExist: return {'error': ''} percent_account = property(get_data_percent_account) def get_data_graphics_pay_date(self): try: pay_date = self.credit.credit_graphics.filter( credit=self.credit, tranche=self.tranche).latest('pay_date') return {'Дата возврата': f'{pay_date.pay_date}'} except ObjectDoesNotExist: return {'error': ''} return_date = property(get_data_graphics_pay_date) views.py: class Test(View): model = None fields = None report_generator = None filename = None form_class = None def get_filtered_queryset(self, queryset, data_dict): filtered_queryset = CreditsTrancheFilterSet(data_dict, queryset=queryset).qs return filtered_queryset def get_filtered_data(self, data_dict): select_related_list = [] for field in self.fields: if '__' in field: select_related_list.append('__'.join(field.split('__')[:-1])) queryset = self.model.objects.select_related(*select_related_list).only(*self.fields).values(*self.fields) # Filter queryset queryset = self.get_filtered_queryset(queryset, data_dict) ... class MyView(Test): model = CreditsTrancheProxy title = 'MyTitle' fields = ('credit__customer__fullname', 'credit__document__number', 'current_account', 'percent_account', … -
Social sign in Django rest framework
For a flutter app, I need to develop some API using Django rest-framework. For the authentication what I have done so far, using simple token auth. When a new user sign-up and then verify his email, I generate a token and that token is then used to send requests. For logout, the token that is generated before needs to be deleted from the front end and redirected to the login page. If the user wants to log in again, the user needs to provide the email and the password. If the credentials are correct, the token is sent again. Now I have to implement Google sign-in. I am confused about the workflow. Can anyone guide me on how to do this same thing? Thanks in advance. -
Django on kubernetes pod no space left on device
So I am running Django App in kubernetes pod at when trying to save an image file: img_obj.image.save(img_file, File(img_file_org)) I am getting no space left error: File "/code/ocr_client/management/commands/pdf_to_image.py", line 126, in handle img_obj.image.save(img_file, File(img_file_org)) File "/opt/conda/lib/python3.7/site-packages/django/db/models/fields/files.py", line 88, in save self.name = self.storage.save(name, content, max_length=self.field.max_length) File "/opt/conda/lib/python3.7/site-packages/django/core/files/storage.py", line 54, in save return self._save(name, content) File "/opt/conda/lib/python3.7/site-packages/django/core/files/storage.py", line 274, in _save fd = os.open(full_path, self.OS_OPEN_FLAGS, 0o666) OSError: [Errno 28] No space left on device: '/code/pca_back_data/media/file1.png' I already ran kubectl exec <my-pod> -- df -ah And there is still 20% of the space left (100GB) I also ran as suggested in other thread: kubectl exec <my-pod> -- df -hi and the usage of inodes was only 5% I am not sure what else might be the issue here? Is there some config in Kubernetes that restricts usage of storage for a pod/process? -
django logging config with gunicorn and command line scripts
Up until now this config LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', } }, 'formatters': { 'verbose': { 'format': '%(asctime)s [%(levelname)s] %(name)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', }, }, } was good enough for me, everything to console then using PYTHONUNBUFFERED=TRUE and gunicorn config bind = "0.0.0.0:50000" workers = 1 worker_class = "gthread" threads = 2 worker_connections = 1000 timeout = 60 keepalive = 5 accesslog = "/var/log/gunicorn/myapp.com-access.log" errorlog = "/var/log/gunicorn/myapp.com-error.log" loglevel = "debug" capture_output = True everything went to accesslog or errorLog. Now that I need to use poetry run python manage.py sqlflush I run into trouble. all my logger.info() logs are also output to console so I get Logging in Logged in Logging in Already logged in BEGIN; SET FOREIGN_KEY_CHECKS = 0; TRUNCATE `myapp_imagemodel`; TRUNCATE `auth_user_groups`; TRUNCATE `auth_user_user_permissions`; TRUNCATE `auth_permission`; TRUNCATE `auth_group_permissions`; TRUNCATE `auth_user`; TRUNCATE `auth_group`; TRUNCATE `django_content_type`; TRUNCATE `myapp_game`; TRUNCATE `myapp_game_screenshots`; TRUNCATE `django_session`; TRUNCATE `django_admin_log`; SET FOREIGN_KEY_CHECKS = 1; COMMIT; How should I configure logging so it doesn't mess up with manage.py script's output? Can I still have it all in one file? -
Python 3.8 running on 64bit Amazon Linux 2/3.5.3 error: ctypes.util.find_library() did not manage to locate a library called 'pango-1.0-0'
I am trying to deploy an app on elastic beanstalk Python 3.8 running on 64bit Amazon Linux 2/3.5.3 server. I have weasyprint and GTK3 installed in my pc. Also 'C:\Program Files\GTK3-Runtime Win64\bin' exists in system environment variables. When I create an environment on elastic beanstalk using: eb create django-env I get an error: OSError: cannot load library 'pango-1.0-0': pango-1.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 'pango-1.0-0' WeasyPrint is running fine on my windows system. But after environment creation on aws elastic beanstalk, I get the error in logs. I already checked here, but its not of much help to windows users -
Java FeignClient REST call to Django webserver throwing SocketTimeoutException
I have two micro services running, one in java tomcat and another in python Django. Java app calls python server using feignclient library. Some times calls are failed due SocketTimeoutException. At that specific time there is no load observed in python server. Ideally python API response in 100ms and we set a timeout of 1sec for feignclient with 2 retries. Please let me know how to handle this situation. -
Splitting admin.py in Django
I'm working on a Django project and have organized my admin-related code in the following file structure: myapp/ admin/ __init__.py common.py admin_a.py admin_b.py In the __init__.py file of the admin package, I'm currently using from .common import *, from .admin_a import *, and from .admin_b import * to import all names defined in the respective files. In a similar fashion, I have a file structure for the filters: myapp/ folder_a/ admin.py folder_b/ admin.py admin.py In the admin.py file at the top level, I'm using from folder_a.admin import * and from folder_b.admin import * to import all names defined in the respective files. My question is: What is the recommended way to split the admin.py file? Should I continue to use import * in the __init__.py and admin.py files, or is there a better approach? I'm concerned about potential namespace pollution, conflicts, and readability issues that may arise from using import *. I want to follow best practices and ensure a clean and maintainable codebase. Any advice or suggestions on the preferred approach for splitting the admin.py file in Django projects would be greatly appreciated. Thank you! -
Page not found (404) Battery not found
the error i am getting this is what the battery_registration_success page looks like I cant get my web application to generate static qr codes. I am building a django web application. My project is "Fake phone battery identification using blockchain technology". The user must enter the phone battery's details to register it in the system. Once successfully registered, the user will be given a unique battery id and a link to generate the qr code. When i click the link i get this error: 2023-06-28 14:08:17 [WARNING] django.request: Not Found: /fontriden/fontriden/qr_code/c549194f808cf837a9595b94b6eba295b902024bfa859f61ae72d589ce6eca59/ [28/Jun/2023 14:08:17] "GET /fontriden/fontriden/qr_code/c549194f808cf837a9595b94b6eba295b902024bfa859f61ae72d589ce6eca59/ HTTP/1.1" 404 5475 this is what my views.py looks like: def battery_registration_success(request): w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:7545")) contract = w3.eth.contract(address=CONTRACT_ADDRESS, abi=contract_abi) battery_id = request.session.get('battery_id') numeric_battery_id = int(battery_id, 16) # Convert hexadecimal string to integer qr_code_url = reverse('qr_code_image', args=(battery_id,)) battery_details = get_battery_details(w3, contract, battery_id) context = { 'battery_details': { 'battery_id': battery_id, 'product_name': battery_details[0], 'certification_mark': battery_details[1], 'serial_number': battery_details[2], 'watt_hours': battery_details[3], 'qr_code_url': qr_code_url, def qr_code_image(request, battery_id): try: battery = Battery.objects.get(id=str(battery_id)) except Battery.DoesNotExist: raise Http404("Battery not found") qr_image = generate_qr_code(battery) qr_image_data = qr_image.getvalue() battery_details = get_battery_details(battery_id) qr_code_filepath = generate_qr_code(battery, battery_details) context = { 'battery_details': { 'battery_id': battery.battery_id, 'product_name': battery_details[0], 'certification_mark': battery_details[1], 'serial_number': battery_details[2], 'watt_hours': battery_details[3], 'qr_code_filepath': qr_code_filepath, } } return render(request, … -
Django Bleach with CKeditor?
Good morning, have you already configured Django Bleach for CKEDITOR? Actually I'm using a form with Django. And I use CKEDITOR to be able to write. But is there a configuration to use Django Bleach with? Because in my template I use |safe. THANKS I want to safe the data send with ckeditor. models.py class Comment(models.Model): content = RichTextField(verbose_name="Message") forms.py class IdeaCommentForm(forms.ModelForm): captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) class Meta: model = Comment fields = ["content"] views.py if request.method == "POST": form = IdeaCommentForm(request.POST) if form.is_valid(): form.instance.user = user form.instance.idea = idea form.save() return redirect(idea) else: form = IdeaCommentForm() hrml <div class="card-body"> <p class="card-text">{{ comment.content|safe }}</p> </div> thks ! -
Proof Key for Code Exchange Error in Microsoft Active Directory
AADSTS9002325: Proof Key for Code Exchange is required for cross-origin authorization code redemption. I have followed this https://learn.microsoft.com/en-us/training/modules/msid-django-web-app-sign-in/1-introduction and got Proof Key for Code Exchange is required for cross-origin authorization code redemption . -
Django - asgi - uvicorn - multithreading
I was trying to find out benefits and shortcomings of using asgi instead of wsgi server with async and sync view when i found that asgi was creating multiple threads for multiple requests. I set up a demo project with 2 views (1 synchronous and 1 asynchronous with time.sleep and asyncio.sleep respectively). Using asgi when i make 500 simultaneous requests for synchronous view it make 500 threads (one for each request which is kind of counter intuitive because i was expecting a single thread to resolve 500 requests 1 by one), and when i make 500 simultaneous request for async view it is still creating 500 threads although when i log the thread id in async view, all requests are being handled by a single thread. I am not using any middleware or extra app that may have any synchronous code to cause this issue. More over i tried unicorn with FASTapi and it worked as expected (a single thread for async code). -
issues with using django inside vagrant
So this was my first time working with vagrant and django and i was following a course where he taught how to make vagrant file and run the virtual machine and inside how to make python virtual environment (named env). Then he taught how to initialize django and everything was working good so far, then using python manage.py runserver 0.0.0.0:8000 i ran the django server and it seemed to work on my chrome, i was seeing that rocket thing with django. The issue arised when i wanted to stop the server. He said to press ctrl+c to exit the server. When i pressed ctrl+c it stopped my vagrant and took me back to the termial (git bash) keeping the vm running in the background. When i tried closing the git bash it told me that vagrant was running do you still want to close it. Even after closing the terminal the server was still running. Does anyone know the way to close the server the correct way as i had to force kill to stop the server using the following commands ps aux | grep runserver and then using this command to kill the runserver kill -9 <PID> Does anyone … -
Apache WSGI IPC
I have a Django app running behind an Apache/ModWSGI server with multiple processes. I'd like to implement a feature where settings, such as model field labels, are stored in the database and dynamically updated in the UI. To avoid this from slowing down each Django request, I don't want to pull all model field names from the database in each request. I just want to pull them from the Django instance first loads, and then update them once if they're changed. It's pretty trivial to create a Django signal to hook onto my field name model, and dynamically update the field's "verbose name" value in memory. However, that only updates the process for that request. The other N-1 processes being run by Apache will still be using the old value. How would I tell the other processes to update a specific setting? Ideally, I want a very light-weight interprocess communication method to push a "field name changed" event to the other processes, which they would then consume and do that lightweight task of updating the value in their memory. There are a ton of multiprocessing tools for Python, but are there any specific ones for a task like this, especially … -
wagtail cms with codered extension how to add a form on the home page
I have content on my homepage using the styles and all available by the coderedcms extension of wagtail I am wondering how can I add a subscribe form for newsletters using the mail chimp integration. here is the refrence link to the extension. https://github.com/coderedcorp/coderedcms -
Django Custom authentication failing to keep user authenticated across requests
I have a custom model that I'm using together with a custom authentication backend: model class Radcheck(AbstractBaseUser, PermissionsMixin): class Operator(models.TextChoices): EQUAL = ':=', ':=' EQUALS = '==', '==' NOT_EQUAL = '!=', '!=' # id = models.BigAutoField(primary_key=True) username = models.TextField(default='') attribute = models.TextField(default='') op = EnumField(Operator, default=Operator.EQUAL) value = models.TextField(default='') package = models.ForeignKey(InternetPackage, on_delete=models.CASCADE, null=True) voucher_status = models.CharField(max_length=2, choices=expiry_choices, default='0') # last_login = models.DateTimeField(null=True) is_active = models.BooleanField(default=True) objects = RadcheckUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] groups = models.ManyToManyField( 'auth.Group', verbose_name='groups', blank=True, related_name='radcheck_users' # Specify a unique related_name for groups ) user_permissions = models.ManyToManyField( 'auth.Permission', verbose_name='user permissions', blank=True, related_name='radcheck_users' # Specify a unique related_name for user_permissions ) class Meta: db_table = 'radcheck' indexes = [ models.Index(fields=['username', 'attribute']), # Use this index if you use case insensitive queries # models.Index(fields=[models.functions.Lower('UserName'), 'Attribute']), ] def __str__(self): return self.username backend class RadiusBackend(BaseBackend): def authenticate(self, request, voucher=None, **kwargs): if request.path.startswith('/admin/'): return None # Return None for admin site requests auth_request = client.CreateAuthPacket( code=pyrad.packet.AccessRequest, User_Name=voucher, NAS_Identifier="Mikrotik" ) auth_request["User-Password"] = auth_request.PwCrypt(voucher) # Send request response = client.SendPacket(auth_request) if response.code == pyrad.packet.AccessAccept: # Authentication successful try: user = Radcheck.objects.get(username=voucher) # if user.is_active: print("------------------------------Done here with AUTH!----------------------------------------") return user except Radcheck.DoesNotExist: # User does not exist, handle accordingly print("----------------Voucher does … -
How to call API view from another View in Django REST framework?
I am trying to call APIView from another APIView, the code similar to: A.views.py from rest_framework import views from rest_framework.response import Response class A(views.APIView): def post(self, request, *args, **kwargs): return Response({"message": "class A"}) B.views.py from rest_framework import views from rest_framework.response import Response from A.views import A class B(views.APIView): def post(self, request, *args, **kwargs): http_response = <call_A_APIView> return Response({"message": http_response}) I have already tried the below code line: http_response = A.as_view()(request._request) But raise the below exception: You cannot access body after reading from request's data stream Any idea how to do it in the right way? -
Error in django that even chatgpt can't fix
error pictures I did post create, delete and update in django, then I created a dropdown to reach these pages. When I added the url extensions, I got an error in the extension, it looks in the pictures above, I asked chat gpt, the answers did not fix the error, whatever I did, it didn't work. -
Airflow task exited when calling django.setup(). No exception messages was printed
Trying to run django task with airflow. Has a local airflow setup. Tried example DAG and worked. Tried "Hello world" PythonOperator and worked. But when calling django.setup(), it exited with no exception message. Task log: *** Found local files: *** * /Users/st/airflow/logs/dag_id=exchange_rate_dag/run_id=manual__2023-06-27T20:16:11.857094+00:00/task_id=update_exchange_rate/attempt=1.log [2023-06-27, 20:16:13 UTC] {taskinstance.py:1103} INFO - Dependencies all met for dep_context=non-requeueable deps ti=<TaskInstance: exchange_rate_dag.update_exchange_rate manual__2023-06-27T20:16:11.857094+00:00 [queued]> [2023-06-27, 20:16:13 UTC] {taskinstance.py:1103} INFO - Dependencies all met for dep_context=requeueable deps ti=<TaskInstance: exchange_rate_dag.update_exchange_rate manual__2023-06-27T20:16:11.857094+00:00 [queued]> [2023-06-27, 20:16:13 UTC] {taskinstance.py:1308} INFO - Starting attempt 1 of 1 [2023-06-27, 20:16:13 UTC] {taskinstance.py:1327} INFO - Executing <Task(PythonOperator): update_exchange_rate> on 2023-06-27 20:16:11.857094+00:00 [2023-06-27, 20:16:13 UTC] {standard_task_runner.py:57} INFO - Started process 6674 to run task [2023-06-27, 20:16:13 UTC] {standard_task_runner.py:84} INFO - Running: ['airflow', 'tasks', 'run', 'exchange_rate_dag', 'update_exchange_rate', 'manual__2023-06-27T20:16:11.857094+00:00', '--job-id', '28', '--raw', '--subdir', 'DAGS_FOLDER/exchange_rate_dag.py', '--cfg-path', '/var/folders/cd/r_7zr7_x6nn32q2rk71pd5cw0000gn/T/tmpfqho3yoo'] [2023-06-27, 20:16:13 UTC] {standard_task_runner.py:85} INFO - Job 28: Subtask update_exchange_rate [2023-06-27, 20:16:13 UTC] {task_command.py:410} INFO - Running <TaskInstance: exchange_rate_dag.update_exchange_rate manual__2023-06-27T20:16:11.857094+00:00 [running]> on host ss-macbook-pro [2023-06-27, 20:16:13 UTC] {taskinstance.py:1545} INFO - Exporting env vars: AIRFLOW_CTX_DAG_OWNER='airflow' AIRFLOW_CTX_DAG_ID='exchange_rate_dag' AIRFLOW_CTX_TASK_ID='update_exchange_rate' AIRFLOW_CTX_EXECUTION_DATE='2023-06-27T20:16:11.857094+00:00' AIRFLOW_CTX_TRY_NUMBER='1' AIRFLOW_CTX_DAG_RUN_ID='manual__2023-06-27T20:16:11.857094+00:00' [2023-06-27, 20:16:13 UTC] {exchange_rate_dag.py:27} INFO - Finish setting stuff [2023-06-27, 20:16:13 UTC] {exchange_rate_dag.py:29} INFO - Finish set django setting modules [2023-06-27, 20:16:15 UTC] {local_task_job_runner.py:225} INFO - Task exited with return code 1 … -
Cannot get ManytoManyField content to display on my web page
I am having trouble accessing a list of data on a through table. The through table is called Cast and has a ManyToManyField for my Movie table (which lists every movie in the database) and another ManyToManyField for my Person table (which lists every actor). The fields need to be ManyToMany because an actor can appear in many different movies, and a movie can contain many different actors. I want to run a for-loop that lists all of the actors associated with a given movie (filtered by the movies primary key) and displays them on a web page. So far I cannot list anything on the web page (Movie.title displays the title, but I can't display anything from the Cast table.) I have tried reading all the other related stackoverflow solutions (such as listing objects from ManyToManyField) but I still cannot get the actor's names to display on the website. /Model.py class Movie(models.Model): title = models.CharField(max_length=250) class Person(models.Model): name = models.CharField(max_length=100) class Cast(models.Model): movie = models.ManyToManyField( Movie, ) castmember = models.ManyToManyField( Person ) /View.py class MoviePageView(TemplateView): template_name = '_movie_info.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['movie'] = Movie.objects.all() context['cast'] = Cast.objects.filter(movie__id=**kwargs) I have also tried: context['cast'] = Cast.objects.filter(movie__id=self.movie.id) context['cast'] = … -
Django urls.py not including the path
I'm relatively new to python and trying to make a django app. Can someone explain me why I'm running in to this issue with the include statement? The sql server says no module named 'website'. I think the problem is with the project structure, but I could not understand how to fix it. from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), # path('login/', views.login, name='login'), # path('logout/', views.logout, name='logout'), ] urls.py file in website folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include(website.urls)) ] urls.py file in crm folder -
uWSGI + Nginx don't generate the .sock file
I'm trying to deploy a Django app with uWSGI and Nginx like I always have done in the last 10 years but this time don't seem to work. Looks like there are permissions issues because the app.sock file is not created. This is my uwsgi.service: [Unit] Description=uWSGI Emperor service [Service] ExecStart=uwsgi --emperor /app/app/deployment/uwsgi.ini Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target This is my uwsgi.ini file: [uwsgi] # Ruta a la raiz del proyecto Django chdir = /app/app # Ruta al archivo wsgi.py del proyecto Django wsgi-file = /app/app/app/wsgi.py # Ruta al virtualenv del proyecto Django home = /app/app/.venv # Process-related settings master = true processes = %k threads = %(%k * 3) # The socket (use the full path to be safe) socket = /tmp/app.sock chmod-socket = 660 chown-socket = debian:www-data uid = www-data gid = www-data # Clear environment on exit vacuum = true # Location of log files logto = /var/log/uwsgi/%n.log # Respawn processes after serving 5000 max-requests = 5000 touch-chain-reload = %dreload listen = 40000 cpu-affinity = 1 max-fd = 200000 memory-report = 1 post-buffering = 1 This is my nginx.conf: server { listen 80; listen [::]:80; server_name 200.100.000.000; # Nuestro dominio o direccion IP charset utf-8; access_log …