Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError in django project [duplicate]
**Hi all i am creating a student login page and gettting the error below, and to my surprise the same code for adminlogin works perfect. I am new to django so kindly clear my doubts to reduce this types of errors in future. Thanks in advance ** ValueError at /studentlogin/ The view myapp.views.studentlogin didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://localhost:8000/studentlogin/ Django Version: 5.0.4 Exception Type: ValueError Exception Value: The view myapp.views.studentlogin didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\Hardip Gajjar\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\base.py, line 332, in check_response Raised during: myapp.views.studentlogin Python Executable: C:\Users\Hardip Gajjar\AppData\Local\Programs\Python\Python312\python.exe Python Version: 3.12.2 Python Path: ['E:\\KantamEducation', 'E:\\KantamEducation', 'C:\\Program ' 'Files\\JetBrains\\PyCharm2023.3\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\Hardip ' 'Gajjar\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\Hardip Gajjar\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\Hardip Gajjar\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\Hardip Gajjar\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Users\\Hardip ' 'Gajjar\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages', 'C:\\Program ' 'Files\\JetBrains\\PyCharm2023.3\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Tue, 23 Apr 2024 11:56:21 +0530 my views.py code is as under, def studentlogin(request): if request.method == 'POST': try: user = Student.objects.get( email=request.POST['email'], password=request.POST['password'] ) request.session['email'] = user.email request.session['fname'] = user.fname return render(request, 'studentindex.html') except: msg = 'Invalid Email or Password' return render(request, 'studentlogin.html',{'msg':msg}) and my student login HTML form code is as under, {% extends 'header.html' %} {% load static %} {% block content %} <!-- Admin Login Page … -
Dependency check with liccheck fails - Expected matching RIGHT_PARENTHESIS for LEFT_PARENTHESIS, after version specifier
In a django app, with poetry as the dependency/packaging manager, I am using a library (also a django one) that is used by multiple django apps. Those different apps are using different versions of django. So, in the pyproject.toml file of the library, the django dependency is defined like so: django = ">=3.2.18,<4.0.0 || >=4.0.10,<4.1.0 || >=4.1.7" while in my application I am have: django="4.1.13" The dependency check with liccheck is done as follows: poetry export --without-hashes -f requirements.txt > requirements.txt liccheck -r requirements.txt After I run the check, it fails for with the following error message: pkg_resources.extern.packaging.requirements.InvalidRequirement: Expected matching RIGHT_PARENTHESIS for LEFT_PARENTHESIS, after version specifier django (>=3.2.18,<4.0.0 || >=4.0.10,<4.1.0 || >=4.1.7) ~~~~~~~~~~~~~~~~~^ It seems that the django dependency from the library is affecting the dependency check. Initially I had the 0.9.1 version of liccheck and I have already updated it to the latest 0.9.2 but with the same results. Any idea? -
Django CloudinaryField: Setting Default Privacy on Upload and Generating Presigned URLs for Public Access
I'm working on a Django project where I have a model Media with an image field stored using CloudinaryField. Currently, I'm able to upload images via multipart/form, and I can generate a public link using media_object.image.url. However, I'm facing two challenges: Default Upload Privacy: How can I set the default privacy of the uploaded images to be private? Generating Presigned URLs: I need to generate presigned URLs for public access to these images, but I want these URLs to expire after a certain period, say 5 minutes. Here's what my current model looks like: from django.db import models from cloudinary.models import CloudinaryField class Media(models.Model): # Other fields... image = CloudinaryField('document', null=True, blank=True) Could someone please guide me on how to achieve these two objectives? Any help or pointers would be greatly appreciated. Thanks! -
(AWS + React + Django) Storing API Keys for my Frontend
I know this question has been asked before and I've reviewed the posts here: How do I hide an API key in Create React App? and here Using API keys in a react app that API keys in React are not secure if stored as environment variables and should instead be retrieved from your backend, other requests are typically handled with cookies and session authentication. I built my application with Django REST Framework for the backend, this is deployed to AWS Beanstalk. My frontend is built on React that I was planning on deploying to S3. I'm still having trouble putting together how this applies in my case though. In my case I have an REST API built that requires SessionAuthentication for all requests except for two that I built in API key authentication for: Logging in and creating a new account. Reason being is because the user wont have an account to authenticate with, but I still wanted to have some sort of authentication built in for my front end. I also wanted to allow the front end to display user data (like a list of users) without requiring a user to be signed in. In these cases, is … -
django create a record in a table with a foreign key
I want to make a new entry in table with foreign key, through the UI The Model: class SchemeMovement(models.Model): id = models.AutoField(db_column='Id', primary_key=True) scheme = models.ForeignKey(Scheme, models.DO_NOTHING, db_column='Scheme_Id', blank=True, null=True) The view: def schmov(request): if request.method == "POST": form = SchememovForm(request.POST) if form.is_valid(): try: form.save() return redirect('/showSchemeMovement') except: pass else: form = SchememovForm() return render(request,'indexSchemeMovement.html',{'form':form}) The html: <form method="POST" class="post-form" action="/schmov"> {% csrf_token %} <div class="container"> <br> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <h3>Enter Details</h3> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Scheme Code:</label> <div class="col-sm-4"> {{ form.scheme.scheme_code }} </div> </div> But get blank on the UI: How to make a new entry through the UI? -
how to change the existing "add to model" url in django admin
enter image description here So like this, I created a proxy model then I registered the proxy model, now I want to create a proxy for this model, when I go to the form, it will be added to the model that the proxy model was created for. model.py class Congregation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) masteruser = models.OneToOneField( Master, verbose_name='Master Data', on_delete=models.CASCADE, related_name='Congregation', ) member_number = models.IntegerField() alias_name = models.CharField(max_length=255) chinese_name = models.CharField(max_length=255) is_congregation = models.BooleanField(default=False) worship_id = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) class Meta: verbose_name = 'Data Jemaat' verbose_name_plural = 'Data Jemaat' def __str__(self): return self.masteruser.full_name model_proxy.py from master.models import Congregation, class CongregationManage(models.Manager): def get_queryset(self): return super(CongregationManage, self).get_queryset().filter( is_congregation=True ) class CongregationProxy(Congregation): objects = CongregationManage() class Meta: proxy = True admin.py class CongregationProxyAdmin(nested_admin.NestedModelAdmin): list_display = ('full_name' ,'alias_name', 'chinese_name', 'member_number', 'address' ) date_hierarchy = 'created_at' def full_name(self, obj): return obj.masteruser.full_name def address(self, obj): return obj.masteruser.address admin.site.register(CongregationProxy, CongregationProxyAdmin) So what I hope is that when the congregationProxyAdmin clicks the add button, the URL will be the first one http://127.0.0.1:8000/admin/master/congregationproxy/add/ become http://127.0.0.1:8000/admin/master/master/add/#group-fs-Congregation--inline-Congregation -
django & nginx & uwsgi deployed service not working
I have an issue with django & nginx & uwsgi, deployed service suddenly stopped with no reason few hours ago, so I don't know where to start debugging. (I'm very new to backend eng.) When I run the virtual environment using py manage.py runserver it works and 'sudo systemctl status uwsgi' 'sudo systemctl status nginx' both are active. But when I try to open the admin site with designated url, it doesn't respond and shows timeout error. there are no problems in ssl certifications(valid until next month), and port is opened normally (80, 443). When I tried ssh connection to the server via vscode it also worked. where should I find the problem? please help -
Fatal error in launcher Unable to create process install package
while i try to install any packages in django i get this error Fatal error in launcher: Unable to create process using '"C:\Users\lenovo\Desktop\PCADI\backend\myVenv\Scripts\python.exe" "C:\Users\lenovo\Desktop\data-collection\backend\myVenv\Scripts\pip.exe" install': Le fichier spÚcifiÚ est introuvable. i solve this issue with the following command : python -m pip then install the package that you want like the following command i try to install django-multiupload in my case : python -m pip install django-multiupload and it's installed Successfully installed django-multiupload-0.6.1 -
Table django_celery_beat_clockedschedule' doesn't exist
django_celery_beat_clockedschedule' doesn't exist I successfully installed django-celery-beat package with django==2.1. All migrations are also applied successfully, There are five models are showing in django such as clocked, crontabs, intervals etc. Although when i open there detailed view it says Table '....django_celery_beat_clockedschedule' doesn't exist. It shows the same error for all of them. Note: I also tried too many time to unapply all migrations and reinstalling the django-celery-beat package with no luck -
Django retrieves old content from the database
I've developed an app using Django 5, tested it on my server and my local, and made it in production on my server. The problem is that when a certain action is taken to write or update a record in the database, it's not reflected in the frontend as if it's returning cached data. This only happens to the version in production on my server. I tried the following: Turned the debugging off. Making sure the content was written to the database. Clearing my local cache. Trying to make CSS changes (It works!), but for database content, it doesn't work and no new data is shown. Trying never cache for that view. Checking if there is middleware caching. Deleting pyc files. Making a change to wsgi.py. Restarting Apache several times. Again, This never happens in my local it's just the server. I've also checked older questions, but nothing helps yet. Note: I'm using Django 5, mySQL, Apache, and WSGI on AWS. Your help is highly appreciated. Thanks! -
Getting "Bad Request" error when implementing Google authentication with Django and Djoser
I followed the instructions in this Medium article (https://medium.com/@nitesht.calcgen/google-authentication-using-django-and-djoser-b0ef5f61a50b) to implement Google authentication in my Django application using Djoser. However, when I try to authenticate with Google, I'm getting a "Bad Request" error. I'm currently at the step where I need to make a POST request to the following endpoint: http://127.0.0.1:8000/auth/o/google-oauth2/?state='xxxx'&code='yyyyy'. Additionally, I'm not receiving the expected access and refresh tokens i have "non_field_errors": [ "Invalid state has been provided." ] Bad Request: /auth/o/google-oauth2/ [22/Apr/2024 20:39:13] "POST /auth/o/google-oauth2/?code=4/0AeaY............ -
Docker container is not started due to error: DATABASES is improperly configured. Please supply the ENGINE value on my Django application
Docker container is not started due to error: DATABASES is improperly configured. Please supply the ENGINE value on my Django application. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '*name*', 'HOST': '*host*', 'USER': '*user*', 'PASSWORD': '*password*' } } I use Docker container in Azure with postgresql database. Can anyone help solving the problem? please tell me if you need more information. Thank you! When I run my application locally my application is working with my production database connected, so that shows that code in application should work and error is in Azure? Right? -
Custom widget in the choice field Django
I'm passing a form to the template. I need from this template to then pass to another template the option that the user has selected. In this case, one of the payment options. I can do this with ChoiceField, select built-in widget=RadioSelect() and so on. But the ChoiceField should look like this: When you select an option, it is highlighted with an orange box. That is, I have no text at all, and I need to pass it to the handler in views.py. I'm using Django 4.0. How do I do that? class CheckoutForm(forms.Form): payment_method = forms.ChoiceField( choices=CHOICES, widget=... ) I tried using mark_safe to insert the code into the second CHOICES element, and then in the template using a loop to output the payment_method, but it didn't work as I expected -
Django allauth linkedin login with oauth 2.0 updated scopes
I am trying to add a "Sign In with Linkedin" button in a django site with allauth. I tried adding the following configuration to the social providers setting - 'linkedin_oauth2': { 'SCOPE': [ 'openid', 'profile', 'email' ], 'FIELDS': [ 'id', 'name', 'given_name', 'family_name', 'email', 'picture' ], 'PROFILE_FIELDS': [ 'id', 'name', 'given_name', 'family_name', 'email', 'picture' ], 'VERIFIED_EMAIL': True } I also tried by removing all fields and profile fields and I get a code successfully on the redirect url but I think it fails for some reason either when exchanging the code for a token or mapping the profile fields. I don't see any errors in logs but I see Social Network Login Failure An error occurred while attempting to login via your social network account. on the callback url. I also tried adding the old scopes - r_liteprofile|r_basicprofile|r_emailaddress but all those scopes throw an error stating that the scope is not authorized for my application. -
AttributeError: 'str' object has no attribute 'as_widget'. How to fix?
Error: Internal Server Error: /posts/v3ttel/44/ Traceback (most recent call last): File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\posts\views.py", line 140, in post_view return render(request, 'post.html', context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 175, in render return self._render(context) ^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\test\utils.py", line 112, in instrumented_test_render return self.nodelist.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in render return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 966, in render_annotated return self.render(context) ^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\loader_tags.py", line 157, in render return compiled_parent._render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\test\utils.py", line 112, in instrumented_test_render return self.nodelist.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in render return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 966, in render_annotated return self.render(context) ^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\loader_tags.py", line 63, in render result = block.nodelist.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in render return SafeString("".join([node.render_annotated(context) for node in … -
Django - How can I pass the model_id of my loop as a parameter in the form url? The form is handled in a seperate view
In my django project, I have a forloop that goes through ModelA. During this loop, I have a form. This form is handled in a seperate view and requires the ModelA_id as a parameter. For some reason, ModelA_id, which fine in the loop, is not passed to the form view and the ModelA_id used by the form is the first one picked it. I have used this logic a few times and I cannot see what I am doing different. question: how can I pass the model_id of in my loop as a parameter in the form url? models class ModelA(models.Model): ModelA_field = models.ForeignKey(FK, null = True, blank=True, on_delete=models.CASCADE, related_name="relatednames") def __str__(self): return str(self.title) + ' - ' + str(self.venue) + ' - ' +str(self.points) views def template_function(request, venue_id): i = ModelA.objects.filter( venue=venue_id).order_by('points') return render(request, 'main/template_function.html', {'i': i}) def form_function(request, venue_id, modela_id): print(f' modela_id: {modela_id}') # prints the first modela_id, but not the one it relates to in the template loop. return redirect(url, {}) url path('form_function/<venue_id>/<modela_id>', views.form_function, name="form-function"), template {% for rewardprogram in reward_program %} <div class="row"> <div class="col"> <p class="small-text">{{ modela.id }}</p> #id is correct </div> </div> <div class="row"> <div class="col"> <a class="" onclick="openForm()"> id:{{modela.id}} #id is correct </a> … -
How can I connect an up-to-date django server to a MySQL 5.1 database? (upgrading the MySQL version is not an option)
I have a MySQL-server that is part of a software system that is not developed by me. Thus it is not possible for me to upgrade that MySQL-server to a newer version, because it might break the software system's ability to interact with that database. I need read access to that database on my public facing django application. The django version is the latest LTS (4.2). Django's documentation lists two database API driver options for MySQL: mysqlclient MySQL Connector/Python Both of these in their most current versions do not support access to MySQL 5.1 servers Option 1. still works on Debian 11, with some overwritten methods in a subclass, but not on Debian 12. How do I ensure that my django application still works, when I upgrade its production server from Debian 11 to 12? I have tried using MySQL Connector/Python with the option use_pure, but it gives me the error django.db.utils.DatabaseError: (1193, "1193 (HY000): Unknown system variable 'default_storage_engine'", 'HY000'). I am unsure what I would have to patch, when subclassing that, in order to restore compatibility with MySQL 5.1. -
I cant use Django ORM at external script
i have a Django app and i try to run an external script (for input some data with ORM) which is located at root of my app folder. I take that error: from InventoryFrontBackEnd.inventory.models import Component import pandas as pd import os import sys #this is a test: print(Component.objects.all()) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. (I use a venv which is located at another folder) As i read i have to set the: DJANGO_SETTINGS_MODULE enviroment variable, i tried many things but dont work. The folder structure is given here: the script i run is the Import_D_components.py thank you! -
Why Django Signals async post-save is locking other async ORM calls?
I have a Django 5 application that use websockets using channels, and I'm trying to switch to AsyncConsumers to take advantage of asyncronous execution for I/O or external API tasks. I already wrote a demo project and everything it's working fine, however in my application I use Django signals, and I have a long I/O task to be performed in the post_save of MyModel, previously implemented using threads: from asyncio import sleep @receiver(dj_models.signals.post_save, sender=MyModel) async def auto_process_on_change(sender, instance, **kwargs): logger.log("Starting Long Save task"); await sleep(30) logger.log("Starting Long Save task"); The websocket consumer that is serving the request is similar to the following: from channels.generic import websocket class AsyncGenericConsumer(websocket.AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() ... async def receive_json(self, message): ... user = await User.objects.aget(id=...) # Authentication code # .... # (eventually) Create MyModel, depending on request type mod = await my_models.MyModel.objects.acreate(...) Now, the problem is as follow: When Alice's request is still performing a post_save operation (i.e., awaiting the long task contained in it) and a Bob user opens up a the browser and makes a request to the same consumer, the computation gets stuck to user = await User.objects.aget(id=...) until the long task (e.g., the asyncio.sleep(30)) terminates for Alice. The … -
Django null value in column with default violates not-null constraint
I have this current table, with state as Jsonfield with default a empty dict class Channel(models.Model): agent = models.ForeignKey(Agent, on_delete=models.SET_NULL, null=True, blank=True) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) type = models.CharField(choices=ChannelType.choices, max_length=64, default=ChannelType.WHATSAPP) settings = models.JSONField(blank=True, default=dict) state = models.JSONField(blank=True, default=dict) disabled = ArrayField(models.CharField(), blank=True, default=list) But when i try to create a Channel Object Channel.objects.create(type=ChannelType.WHATSAPP, settings=serializer.validated_data, organization=user_utils.get_user_organization(request.user)) Django raises this error django.db.utils.IntegrityError: null value in column "state" of relation "core_channel" violates not-null constraint Failing row contains (4, WHATSAPP, {"session_id": "611a09fd-ccfd-4683-ba92-4717c9688193"},null, {}, null, 1). Why? default should not make that the default value a {}? why is working with the field disabled? -
When I try to install Pillow, I encounter this error
(env) PS D:\programing\source\Backend\Django> python -m pip install Pillow Collecting Pillow Using cached pillow-10.3.0.tar.gz (46.6 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: Pillow Building wheel for Pillow (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for Pillow (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [216 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.mingw_x86_64-cpython-311 creating build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\BdfFontFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ContainerIO.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\CurImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ExifTags.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\features.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FitsImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FliImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FontFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GdImageFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GifImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GimpGradientFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\Image.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ImageChops.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ImageCms.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ImageColor.py -> build\lib.mingw_x86_64-cpython-311\PIL copying … -
Django prefetch_related filtered by an attribute of the outer query
I am working on a simple Django application that stores and shows programmes for events: There is a table of Participants, which are also used in Django's auth system. Each Participant can have multiple Affiliations with a number of Institutes. Each Affiliation has a (nullable) start and end timestamp. Each Slot represents a single activity (talk, meal, workshop) and has a start timestamp. Multiple people can be assigned to each slot. class Participant(models.Model): name = models.CharField(max_length=256) institutes = models.ManyToManyField('Institute', through='Affiliation', related_name='people') class Institute(models.Model): name = models.CharField(max_length=256) class Affiliation(models.Model): person = models.ForeignKey('Participant', on_delete=models.CASCADE, related_name='affiliation') institute = models.ForeignKey('Institute', on_delete=models.CASCADE, related_name='affiliation') start = models.DateField(null=True, blank=True) end = models.DateField(null=True, blank=True) class Slot(models.Model): title = models.CharField(blank=True, max_length=256) abstract = models.TextField(blank=True, max_length=4096) start = models.DateTimeField(null=True, blank=True) person = models.ManyToManyField('Participant', related_name='slots', blank=True) I would like to show a single Slot and the people responsible, along with their Affiliations, but only those that are valid at the beginning of that event (where start is null or earlier than Slot.start, and end is null or later than Slot.start). I have written a QuerySet method for that, and by itself it is working correctly, as I could verify with manage.py shell: class ParticipantQuerySet(models.QuerySet): def with_current_affiliations(self, date: datetime.date = None): date … -
Django redirect not working if called inside a function
I would like to put a redirect command inside of a function and then call this function in a Django view. Can anyone give me a hint why my code below does not redirect? This redirection works: views.py from django.shortcuts import redirect from django.http import HttpResponse def my_view(request): return redirect("https://stackoverflow.com") return HttpResponse("<p>redirection did not work</p>") This redirection does not work: views.py from django.shortcuts import redirect from django.http import HttpResponse # define subfunction def test(): return redirect("https://stackoverflow.com") def my_view(request): test() return HttpResponse("<p>redirection did not work</p>") -
Hosting Django from a directory
My directory structure is like so: C:\htdocs # web root |_ django-container +- django-project | +- core # startproject | |_ myapp1 # startapp +- public +- static # STATIC_ROOT, collectstatic | +- css | +- images | |_ js |_ media # MEDIA_ROOT Nginx config: http { # ... upstream wsgi-server { server 127.0.0.1:8080; } server { # ... location /myloc/ { proxy_pass http://wsgi-server/; } location /myloc/public/media/ { alias C:/htdocs/django-container/public/media/; autoindex off; } location /myloc/public/static/ { alias C:/htdocs/django-container/public/static/; autoindex off; } } } I run a waitress WSGI server as a service on port 8000 that runs core.wsgi.application. My settings.MEDIA_URL and settings.STATIC_URL are public/media/ and public/static/ respectively. When I do redirects in my app, or create urls in templates, it doesn't have the myloc segment, because of which all links fail. Even the public/static/ and public/media/ links. For the last 2, I could add the segment to settings.STATIC_URL and settings.MEDIA_URL, but I wanted a common way to add the myloc segment at all places, preferably automatically if possible. -
How to assign content type automatically when serving a file in Django
I have a system where certain permissions are needed to view files, and I'm using django-guardian for the permissions. I want the file to be displayed in a new tab if the browser supports it, otherwise just download the file. I can check the filename and manually set content type depending on the file extension, but there are too many and it seems like a stupid thing to do. Here is the view: @login_required def ViewDocument(request, document_id): document = Document.objects.get(id=document_id) path = document.file.name # Check user permissions to view file if not request.user.has_perm('home.view_document', document): return HttpResponseForbidden("You don't have permission to access this media.") # Construct the full path to the media file media_path = os.path.join(settings.MEDIA_ROOT, path) # can i do this more easily? if path.endswith('.pdf'): temp_content_type = "application/pdf" elif path.endswith('.png'): temp_content_type = "image/png" elif path.endswith('.jpg'): temp_content_type = "image/jpeg" else: temp_content_type = "application/octet-stream" # Serve the file with open(media_path, 'rb') as file: response = HttpResponse(file.read(), content_type=temp_content_type) return response