Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I get configure error when i try to launch my site in debug mode
Here's my manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webstore.settings') # webstore is project name try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() Here's the error: ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I've tried to set environment manually, nothing changed -
How to fix django-filer 404 error on DigitalOcean?
I have a django-cms app running on DigitalOcean. Creating folders and uploading files with filer works perfectly. When downloading the uploaded files I get a 404 Error - for example on this url: https://my_app.ondigitalocean.app/en/media/filer_public/39/d9/39d9ff20-1aa8-48e5-9b8f-113fc71e534b/atest.pdf/ The file is present in the filesystem: Everything is working on the local development server. -
ImportError error for a project running on apache: DLL load failed while importing cv2
Importing opencv before deployment worked fine for my django project, but deploying to apache was an error. Later I wrote a project that only used opencv to read images, but still deployed to apache with errors. [Wed Jul 03 15:44:57.683431 2024] [mpm_winnt:notice] [pid 8204:tid 392] AH00455: Apache/2.4.59 (Win64) mod_wsgi/4.9.2 Python/3.8 configured -- resuming normal operations [Wed Jul 03 15:44:57.683431 2024] [mpm_winnt:notice] [pid 8204:tid 392] AH00456: Apache Lounge VS17 Server built: Apr 4 2024 15:03:17 [Wed Jul 03 15:44:57.683431 2024] [core:notice] [pid 8204:tid 392] AH00094: Command line: 'F:\\bushu\\code\\Apache24\\bin\\httpd.exe -d F:/bushu/code/Apache24 -f F:\\bushu\\code\\Apache24\\conf\\httpd-cv2_text.conf' [Wed Jul 03 15:44:57.693432 2024] [mpm_winnt:notice] [pid 8204:tid 392] AH00418: Parent: Created child process 3884 [Wed Jul 03 15:44:58.058334 2024] [mpm_winnt:notice] [pid 3884:tid 396] AH00354: Child: Starting 64 worker threads. [Wed Jul 03 15:45:53.993438 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] mod_wsgi (pid=3884): Exception occurred processing WSGI script 'F:/bushu/code/code/cv2_text/cv2_text/wsgi.py'. [Wed Jul 03 15:45:54.085121 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] Traceback (most recent call last):\r [Wed Jul 03 15:45:54.085121 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] File "F:\\bushu\\code\\Python38\\lib\\site-packages\\django\\core\\handlers\\exception.py", line 55, in inner\r [Wed Jul 03 15:45:54.085121 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] response = get_response(request)\r [Wed Jul 03 15:45:54.085121 2024] [wsgi:error] [pid 3884:tid 1168] [client 127.0.0.1:57001] File "F:\\bushu\\code\\Python38\\lib\\site-packages\\django\\core\\handlers\\base.py", … -
celery cannot connect to redis in docker:kombu.exceptions.OperationalError: Error -3 connecting to redis:6379. Lookup timed out
I'm building a Websocket service in Django, and I chose celery to push messages。But when I run celery using eventlet on the online server, the following error occurred: Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in <module> sys.exit(main()) ^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) ^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/bin/celery.py", line 236, in main return celery(auto_envvar_prefix="CELERY") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 1157, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 1078, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/core.py", line 783, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/click/decorators.py", line 33, in new_func return f(get_current_context(), *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/bin/base.py", line 134, in caller return f(ctx, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/bin/worker.py", line 348, in worker worker = app.Worker( ^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/worker/worker.py", line 93, in __init__ self.app.loader.init_worker() File "/usr/local/lib/python3.12/site-packages/celery/loaders/base.py", line 110, in init_worker self.import_default_modules() File "/usr/local/lib/python3.12/site-packages/celery/loaders/base.py", line 104, in import_default_modules raise response File "/usr/local/lib/python3.12/site-packages/celery/utils/dispatch/signal.py", line 276, in send response = receiver(signal=self, sender=sender, **named) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/fixups/django.py", line 97, in on_import_modules self.worker_fixup.validate_models() File "/usr/local/lib/python3.12/site-packages/celery/fixups/django.py", line 135, in validate_models self.django_setup() File "/usr/local/lib/python3.12/site-packages/celery/fixups/django.py", line 131, in django_setup django.setup() File "/usr/local/lib/python3.12/site-packages/django/__init__.py", line 24, in setup … -
How to logout with django rest framework?
I have a django rest framework. And I am using version 5.0.6 and djangorestframework==3.14.0 And I try to implement the logout function. What I already tried? I followed several recourses. For example this one: https://stackoverflow.com/questions/58283277/user-logout-by-session-in-django-rest-framework So my logout looks: from django.contrib.auth import logout class LogoutView(APIView): def get(self, request, format=None): logout(request) return Response(status=status.HTTP_200_OK) url: path('logout/',views.LogoutView.as_view(), name='logout'), and part of settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg', 'corsheaders', 'rest_framework.authtoken', 'django_filters', "accounts", "core", 'drf_spectacular', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] So when I loged in and then I choose for logout then the user will be redirected to url: http://127.0.0.1:8000/api-auth/logout/?next=/api/ And I got this message: This page isn’t working If the problem continues, contact the site owner. HTTP ERROR 405 And I also tried with post. And I still don't understand which HTTP call you need for logout? Is it get or post? Because in the link I have found it is written with a get option. Question: how to build logout function in django rest framework? -
Not logging to /opt folder in rhel
I have a django application that runs in a docker container. I have a defaults.py file which defines the LOGGING configurations, i have included a file handler in the logging configuration to log to files. ‘file’: {‘class’: ‘logging.FileHandler’, ‘filename’: ‘/opt/tejcli/release/log/temp.log’, ‘formatter’: ‘simple’}, Above piece of code is the file handler that i have included. Unfortunately no logs are being written to the temp.log and not even a file is being created. I have manually created the tejcli/release/log folders. I wrote a python script and put it in home directory and tried writing logs to the same folder and it works. How do i solve this? -
Nested Serializer Doesn't work as expected in pytest
I have this serializer class. class CourseListSerializer(serializers.Serializer): course_slug = serializers.CharField() duration = serializers.FloatField() class CourseAssignSerializer(serializers.Serializer): first_name = serializers.CharField(max_length=255) last_name = serializers.CharField(max_length=255) email = serializers.EmailField(max_length=255) username = serializers.CharField(max_length=255) courses = CourseListSerializer(many=True) class CourseAssignListSerializer(serializers.Serializer): users = CourseAssignSerializer(many=True) This is the viewset action class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet): serializer_class = UserSerializer queryset = User.objects.all() lookup_field = "id" authentication_classes = ( ARestAuthentication, BRestAuthentication, ) permission_classes = (permissions.IsAuthenticated | HasAPIKeyWithPermission,) resource_label = "users.User" @action( methods=["put"], detail=False, serializer_class=CourseAssignListSerializer, url_path="assign-course", ) def assign_course(self, request: Request): serializer = self.get_serializer_class()( data=request.data, context={"request": request} ) serializer.is_valid(raise_exception=True) serializer.update(None, serializer.validated_data) return Response(status=status.HTTP_200_OK, data=serializer.data) Above serializers and viewset is working fine when I hit the endpoint using postman. But when I want to put it on the test it giving validation error. I am using the same data when test it on postman and the pytest This is my test function def test_UserViewSet_assign_course(user): request = APIRequestFactory().put( "/api/users/assign-course/", data={ "users":[ { "first_name": "John", "last_name": "doe", "email": "jd@example.com", "username": "jd", "courses": [ { "course_slug": "course_slug", "duration": 30 } ] } ] } force_authenticate(request=request, user=user) action = UserViewSet.as_view( actions={"put": "assign_course"}, serializer_class=CourseAssignListSerializer ) response: Response = action(request=request) print(response.data) assert response.status_code == 200 It giving me {'users': [ErrorDetail(string='This field is required.', code='required')]} But when I use empty data … -
Django: User Profile Update Form Only Showing One User's Data
I'm building an e-commerce website using Django, and I'm having trouble with updating user profiles. I want to display a list of users and provide a way to view and update each user's profile. However, I'm currently only able to see and update the profile of the logged-in user. Here is my current implementation: views.py: def user_list(request): users = CustomUser.objects.all() return render(request, 'useradmin/user_list.html', {'users': users}) @login_required def user_profile_update(request): try: profile = Profile.objects.get(user_name=request.user) except Profile.DoesNotExist: return render(request, 'useradmin/error.html', {'message': 'Profile does not exist.'}) if request.method == "POST": image = request.FILES.get("image") full_name = request.POST.get("full_name") phone = request.POST.get("phone") Address = request.POST.get("Address") diamond_user = request.POST.get("diamond_user") golden_user = request.POST.get("golden_user") if image: profile.image = image profile.full_name = full_name profile.phone = phone profile.Address = Address profile.diamond_user = diamond_user == 'on' # Checkbox values need special handling profile.golden_user = golden_user == 'on' profile.save() messages.success(request, "Profile updated successfully") return redirect("useradmin:user_profile_update") context = { "profile": profile } return render(request, 'useradmin/userprofile.html', context) urls.py: path('user_profile_update/', views.user_profile_update, name='user_profile_update'), path('user_list/', views.user_list, name='user_list'), user_list.html: {% extends 'useradmin/base.html' %} {% block content %} <h1>User List</h1> <ul> {% for user in users %} <li> {{ user.email }} ({{ user.first_name }} {{ user.last_name }}) <a href="{% url 'useradmin:user_profile_update' %}">View/Update</a> </li> {% empty %} <li>No users found.</li> {% endfor … -
Jitsi UI not being updated
I am using Jitsi Meet for video call in one of projects of mine. I cloned the project using link https://github.com/jitsi/jitsi-meet and connected with my react app and is working well.Now I want to change the UI of jitsi meet ,for this purpose I went to documentation ,I followed the steps of i changed into interface.config.js file and title.html file but they are not changed ,so then i build it using "make source-package " it gives me error: p: cannot stat 'build/close3.min.js.map': No such file or directory cp \ node_modules/@jitsi/rnnoise-wasm/dist/rnnoise.wasm \ libs cp -R \ node_modules/@jitsi/excalidraw/dist/excalidraw-assets \ libs/ cp \ react/features/stream-effects/virtual-background/vendor/tflite/.wasm \ libs cp \ react/features/stream-effects/virtual-background/vendor/models/.tflite \ libs cp \ node_modules/lib-jitsi-meet/dist/umd/lib-jitsi-meet.* \ libs cp \ node_modules/@matrix-org/olm/olm.wasm \ libs cp \ node_modules/@tensorflow/tfjs-backend-wasm/dist//*.wasm \ libs ./node_modules/.bin/sass css/main.scss css/all.bundle.css && \ ./node_modules/.bin/cleancss --skip-rebase css/all.bundle.css > css/all.css && \ rm css/all.bundle.css ([ ! -x deploy-local.sh ] || ./deploy-local.sh) cp \ node_modules/@vladmandic/human-models/models/blazeface-front.bin \ node_modules/@vladmandic/human-models/models/blazeface-front.json \ node_modules/@vladmandic/human-models/models/emotion.bin \ node_modules/@vladmandic/human-models/models/emotion.json \ libs mkdir -p source_package/jitsi-meet/css && \ Anyone help me in updating my UI? I wanted to change the UI of jitsi meet and it was unable to be done -
Should I place react files inside of venv directory when making django + react app?
So, I'm new to django and new to react but I thought I'd combine them to make a nice project with a frontend and backend separate. I plan to deploy the frontend on s3 and backend on ec2. Side question but please let me know if this is viable. I'm starting with making the backend template. However, it's recommended that I do my python development inside of a virtual environment, which I understand. Should my file structure be: AppName/ backend/ venv/ - set up django starting here - frontend/ - set up react - Or should I try to put everything inside of the venv. I tried to set it up based on a tutorial and ended up not understanding where anything is (https://www.geeksforgeeks.org/how-to-connect-django-with-reactjs/). Also, it was very unorganized. I'm now restarting and going based solely on documentation, which might be a better approach learning-wise. I think the separating structure is better because I could just upload the entire venv to ec2. Not sure how ec2 set up works but I'll get there eventually. Just wanted some insight to avoid having to restructure everything. Any and all information would be super helpful! -
django FormView modify fields before validation
Is there a proper way to modify the form fields before validating the data on a Class Based FormView. More specifically a CreateView. Is necessary to use Class Based views 'cause I'm throwing in a bunch of custom mixins: class Create(HtmxRequiredMixin, CreatedByMixin, HxFormValidationMixin, BaseMixin, CreateView): template_name = 'administration/form.html' model = Object form_class = Form success_url = reverse_lazy('object-list') hx_retarget = '#CREATE' base = 'object' views_list = ('create',) I used the CreatedByMixin in the DRF viewset for the api rest. it looks like: class CreatedByMixin: def create(self, request, *args, **kwargs): data = request.data.copy() if request.user.is_authenticated: data['created_by'] = request.user.id serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I want a similar mixin for my CreateView but I'm not sure what is the proper method to override. Also, the HxFormValidationMixin already override the form_valid and form_invalid methods. -
Why is my Django app unable to find my URL pattern?
My Django project is run in Docker and I use Celery to handle queuing. When a user submits an audio file the system starts an asynchronous task(that transcribes the audio), continuously checks its progress, and updates the UI once the transcription is complete, with a download button. However I've been getting an error after the transcription completes but before the download button appears. The error indicates that it can't find the view that provides the completed transcript to the user. Here's my code. views.py: def initiate_transcription(request, session_id): file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') if request.method == 'GET': if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) if request.method == 'POST': try: if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: print(str("VIEW: "+session_id)) task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) return JsonResponse({'status': 'success', 'task_id': task.id}) except Exception as e: return JsonResponse({'status': 'error', 'error': 'No file uploaded'}) return render(request, 'transcribe/transcribe-complete-en.html') def check_task_status(request, session_id, task_id): task_result = AsyncResult(task_id) if task_result.ready(): transcribed_doc = TranscribedDocument.objects.get(id=session_id) return JsonResponse({ 'status': 'completed', 'output_file_url': transcribed_doc.output_file.url }) else: return JsonResponse({'status': 'pending'}) JS: form.addEventListener('submit', function(event) { event.preventDefault(); const transcribeField = document.querySelector('.transcribe-output-lang-select') const errorDiv = document.querySelector('.error-transcribe-div'); transcribeField.style.opacity = '0'; setTimeout(function() { transcribeField.style.display = 'none'; … -
Can I define a field in a django model to return data from another model that meets certain conditions?
I have a model for recipes. I have a model for reviews of those recipes. The recipe's author (chef) can select a specific review as their favorite. I think I've set the constraint up correctly to only allow one favorite review per recipe. Let's assume one favorite review per recipe. I would like to reference the one favorite review using the recipe model. Is this possible? Example template snippet below. {% for recipe in recipes %} <div> <h2>{{ recipe.name }}</h2> <p>{{ recipe.favoriteReview.content }} <small>by {{ recipe.favoriteReview.author }}</small></p> <p>Email the chef: {{ recipe.chef.email }}</p> </div> {% endfor %} Here's an example of the models but I feel like I've approached this from the wrong direction and I've hit a wall. # Models as example class User(AbstractUser): pass class Recipe(models.model): name = models.CharField(max_length=64) instructions = models.TextField(max_length=1000) chef = models.ForeignKey("User", on_delete=models.SET_NULL, related_name="recipes") #favoriteReview = The review with chefsFavorite=True and recipe matches this recipe class Review(models.model): author = models.ForeignKey("User", on_delete=models.SET_NULL, related_name="reviews") rating = models.DecimalField(max_digits=2, decimal_places=2) content = models.TextField(max_length=1000) chefsFavorite = models.Boolean(default="True") recipe = models.ForeignKey("Recipe", on_delete=models.CASCADE, related_name="recipes") class Meta: constraints = [ models.UniqueConstraint(fields=['recipe'], condition=models.Q(chefsFavorite=True), name="chefs_one_favorite_recipe_review" ] -
How to validate Post arguments in Django
I've seen plenty of solutions on how to validate Form field parameters, but I am not using Django templates or implementing the front-end in Django at all. I'm looking purely for server-side backend validation. Let's say I have @api_view(['POST']) def my_func(request): And I want the data to be something like: { "username" : <user>, "password" : <pw>, "age" : <age> } I want to validate that username and password are strings, perhaps with a minimum length requirement. And that age is a number, again, perhaps with other restrictions, such as min/max. Is there a standard way to do this? -
Find periodic task's next execution time in Celery Beat
I am creating PeriodicTasks for opening user an access to the next lesson using this code: task = PeriodicTask.objects.create( interval=enrolment.course.interval, name=f"enrolment_id: {enrolment.id}", task="courses.tasks.next_program", args=json.dumps([enrolment.id]), ) enrolment.task = task enrolment.save() How to get datetime next task will be ran? -
Add 'business context' to all views Django
I've got an app handling a store, with some view of Items that are sold there and some list of Employees there etc. Now, there will be the second (physical) store, and my application is not ready for handling more than one :) So to my models will be added Location model, and foreign keys added to Item and Employee... But my question is how to rebuild views ... So my view that lists all Items, should have added some filter on the top to select location and than filter list based on that selection... and Employee view the same (and all other the same).... So - having that filter there on the top, I should set some global ('session'?) variable, and based on that filter each view? (or add it in url parameters?? or any other way?) Please advise me how to do it an elegant way. -
Disable logging of `exc_info` when raising `BadRequest`?
When a Http404 is raised, the log provides the relevant information but not the details of the exception But when a BadRequest is raised, the log includes exc_info so it makes it look like something went wrong rather than standard error handling of bad requests. So is there a way to disable or modify this behavior? -
how to customize all-auth errors for mismatch passwords to othere languge?
class PasswordVerificationMixin(object): def clean(self): cleaned_data = super(PasswordVerificationMixin, self).clean() password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") if (password1 and password2) and password1 != password2: self.add_error("password2", _("You must type the same password each time.")) return cleaned_data I want to override this class and make the error message to 'this a test' i am stuck i tried overriding it but nothing any help? I want to override this class and make the error message to 'this a test' i am stuck i tried overriding it but nothing any help? -
How to get csrfToken for front-end to submit logins in Django
I've read all the issues about this, but it's still not clear to me. I am not using Django templates to handle login functions (login, logout, changepassword, create user, etc). I tried POSTing to the accounts/login page with "username": <user>, "password": <password> But it also wants a CsrfViewMiddleware token. It's not clear to me where I get that. Does the front-end have to requrest it first from another endpoint? Is there some other way to do the CSR checking? -
CORS Policy Error with Specific Data in React and Django Application
CORS Policy Error with Specific Data in React and Django Application I'm experiencing an issue with CORS policy in my React frontend and Django backend application. The error message I'm receiving is: Access to fetch at backend URL' from origin 'frontend URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I have configured all the CORS Configuration in settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with',] Installed apps also 'corsheader' is added The problem is i am getting this issue for only one data not for all data for my views i added Decorators like: @csrf_exempt @require_http_methods(["OPTIONS", "POST"]) As it is working fine in Local,Development only for Staging i am getting this issue that to for only some data others are working fine -
custom storage-backend class not working as expected with s3, boto3 and django-storages
I am following this tutorial here from Michael Herman, trying to setup s3 storage for my django project and I am facing some issues right from the start of the tutorial. First, when I tried running the collectstatic command, I got this error: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied I looked up a bit, and apparently you have to set AWS_DEFAULT_ACL = None and doing that fixed it. So now my static files were being uploaded to the s3 bucket when I ran collectstatic. But when I visited the webpages, the static images and stylesheets were not getting fetched as expected. I tried many different things at this point, but none of them worked. I typed the s3 object url in the browser and this was the error I was getting: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>419CX01JK1CAKYCS<RequestId> <HostId>rB7y8qLl5a5G0I1LVx2lexUbJpcvnrdKIMZ3AVq69C81B3j4BRWZwLq5THNLINwSv6q5HFSAednN1yq2tRCQ6THuxEn+S/Kj</HostId> </Error> Now the next thing I did was to make all the bucket objects as public. The tutorial doesn't do this and I'm not sure if its a bad thing or not? Anyone please point out if it is. Using this answer, I set the Block all public access setting to off and also added a Bucket … -
Bootstrap modal does not trigger inside a django for loop
I want to attach a modal to all images. But for some reason the modal is not triggered and the entire page becomes un-clickable. I have made sure that all modals triggers and modal have a unique ID without any results. Can anyone see what I am doing wrong? {% for photo in user_photos %} <div class="image-container"> <div class="image-wrapper" data-bs-toggle="modal" data-bs-target="#photoModal{{photo.id}}"> <img src="{{ photo.photo.url }}" alt="Användarbilder"> {% if request.user == photo.user %} <form method = "POST"> {% csrf_token %} <i class="bi bi-x-lg profile_delete_photo" title="Radera" data-photoId = "{{photo.pk}}" data-url = "{% url 'profilepage_app:deletePhotoAjax' %}"></i> </form> {% endif %} </div> <span>Uppladdat: {{ photo.timesince }}</span> <!-- Modal --> <div class="modal fade" id="photoModal{{photo.id}}" tabindex="-1" aria-labelledby="photoModallabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="photoModal{{photo.id}}Label">Modal title</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> {% endfor %} I also have this for loop and modal in another page, but it works fine. {% for diary in user_diaries %} <tr> <td> <!--Diary title--> <a href="{{diary.get_absolute_url}}">{{diary.title|truncatechars:30}}</a> {% if request.user == user %} <div> <!--Dropdown--> <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false" fill="currentColor" class="dropdown-toggle bi bi-three-dots-vertical" … -
Error while using django-vite-plugin and react
I am using django-vite-plugin and react for the frontend of my project. I followed the tutorial on https://react.dev/learn/add-react-to-an-existing-project and when testing using index.js I got the error '[vite] Internal server error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.' I would like to kindly ask for assistance solving this problem. I first tried this and got an error import { createRoot } from 'react-dom/client'; document.body.innerHTML = '<div id="app">JS working</div>'; const root = createRoot(document.getElementById('app')); root.render(<h1>Hello</h1>); However when I commented out the last line it worked. LIke this: import { createRoot } from 'react-dom/client'; document.body.innerHTML = '<div id="app">JS working</div>'; const root = createRoot(document.getElementById('app')); //root.render(<h1>Hello</h1>); My index.html is {% load vite %} <!DOCTYPE html> <html lang="en"> <head> <!--Other elements--> <!--Vite dev client for hmr (will not be displayed on production)--> {% vite %} {% vite 'newspaper/css/styles.css' 'newspaper/js/main.js' %} </head> <body> <!--Page content--> </body> </html> My vite.config.js is //vite.config.js import { defineConfig } from 'vite' import { djangoVitePlugin } from 'django-vite-plugin' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [ djangoVitePlugin([ 'newspaper/js/app.js', 'newspaper/css/style.css', ]), react() ], }); My package.json is { … -
Drop duplicates when quering multiple tables in Django
I have a custom manager with search, which orders return results by rank: class MyManager(models.Manager): def search(self, query, fa, fb=None, fc=None, fd=None, qs=None): if not qs: qs = self.get_queryset() try: if not (1 in [c in query for c in '&|()!*:"']): query = " & ".join([f"{q}:*" for q in query.split()]) vector = SearchVector(*fa, weight="A", config="english") if fb: vector += SearchVector(*fb, weight="B", config="english") if fc: vector += SearchVector(*fc, weight="C", config="english") if fd: vector += SearchVector(*fd, weight="D", config="english") query = SearchQuery(query, search_type="raw") qs = ( qs.annotate(search=vector, rank=SearchRank(vector, query)) .filter(search=query) .order_by("-rank", "-id") .distinct("rank", "id") ) qs.count() # Trigger exception except (ProgrammingError, UnboundLocalError): qs = qs.none() return qs But when I try searching on related fields, it still returns duplicate results: class Case(models.Model): machine = models.ForeignKey(Machine, on_delete=models.CASCADE) user = models.ForeignKey(Profile, on_delete=models.SET_NULL) hashtags = models.CharField(max_length=255) closed = models.BooleanField(default=False) objects = MyManager() class CaseProgress(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE) desc = models.TextField() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) class CaseListView(ListView): model = Case def get_queryset(self): query = self.request.GET.get("query", None) show_closed = ( True if self.request.GET.get("show_closed", False) == "true" else False ) if query: if not show_closed: qs = self.model.objects.filter(closed=False) else: qs = self.model.objects.all() fa = ( "id", "machine__serial_number", "machine__company__name", "user__user__first_name", "user__user__last_name", ) fb = ("hashtags",) fc … -
Coloured output from native Django test runner
I'm trying to get a colored output (red or green) when running my Django tests with the native Django test runner. I'm running a poetry virtualenv (python 3.11.6) with Django (5.0.3) and colorama (0.4.6) in a zsh on MacOS but the output remains colourless. Following the Django documentation, I've set export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta" in my zsh before calling python manage.py test apps.myapp. Yet, the output remains colourless. Same result when adding the --force-color option. However, spinning up the same virtualenv and executing from colorama import Fore, Style print(Fore.RED + 'This is red text' + Style.RESET_ALL) returns a red text (as expected). What do I have to do to get a colored output from the native Django test runner without switching to a different one?