Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
convert image to resp(<class 'urllib3.response.HTTPResponse'>) type in Django
previous code : resp = requests.get(IMAGE_API, params={'empid': employee_id}, stream=True).raw return resp resp type is <class 'urllib3.response.HTTPResponse'> now i want to resize this image and return in 'resp form'. How to do it? image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) imageResized = cv2.resize(image, (0,0) , fx = ratio, fy = ratio ) imageResized type is <class 'numpy.ndarray'> how can i convert imageResized to 'resp' type ? -
How to save recorded video file to my filesystem with Javascript and Django?
I'm working on a site where users can make a video from themselves. I'm using Django but I'm not so familiar with advanced JavaScript. I'm using JavasScript code to record the video which is not my code I found it. It works well and downloads the recorded video but I like to save the video to my filesystem instead of download and upload manually or send it to a fileinput with the /documents/videointerview path to save. html <div id="container mx-auto"> <video id="gum" class="mx-auto w-50 d-flex justify-content-center" autoplay muted></video> <video id="recorded" class="mx-auto w-50 d-flex justify-content-center" playsinline loop></video> <div class="my-5"> <button class="btn btn-primary" id="start">Start camera</button> <button class="btn btn-success" id="record" disabled>Record</button> <button class="btn btn-warning" id="play" disabled>Play</button> <button class="btn btn-secondary" id="download" disabled>Download</button> </div> <div class="m-3"> <h4 class="text-info">Video Stream Options</h4> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="echoCancellation"> <label class="form-check-label text-center" for="flexSwitchCheckDefault">Echo Cancellation</label> </div> </div> <div> <span id="errorMsg"></span> </div> </div> js let mediaRecorder; let recordedBlobs; const errorMsgElement = document.querySelector('span#errorMsg'); const recordedVideo = document.querySelector('video#recorded'); const recordButton = document.querySelector('button#record'); const playButton = document.querySelector('button#play'); const downloadButton = document.querySelector('button#download'); recordButton.addEventListener('click', () => { if (recordButton.textContent === 'Record') { startRecording(); } else { stopRecording(); recordButton.textContent = 'Record'; playButton.disabled = false; downloadButton.disabled = false; } }); playButton.addEventListener('click', () => { const superBuffer … -
Django 3.2/Django-cms 3.11: LookupError: Model 'accounts.CustomUser' not registered
I am encountering an issue when trying to add PlaceholderField from cms.models.fields in my events.models module to the EventVenue model. from cms.models.fields import PlaceholderField class EventVenue(models.Model): name = models.CharField(_('name'), max_length=255) slider = PlaceholderField('room_slider') the settings: INSTALLED_APPS = [ 'modeltranslation', 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.forms', 'haystack', 'accounts', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'simple_history', 'crispy_forms', 'crispy_bootstrap5', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_forms', 'django_flatpickr', 'phonenumber_field', 'bgv_cms', 'ddz_cms', 'events', 'mail_list', ] AUTH_USER_MODEL = 'accounts.CustomUser' the custom user class: class CustomUser(AbstractUser): organization = models.ForeignKey(Organization, on_delete=models.SET_NULL,blank=True, null=True, related_name='employee') mailing_list = models.ManyToManyField(to='MailList', related_name='mail_list', blank=True, verbose_name=_('Mailing lists')) room = models.CharField(_('Room Mailing Lists'), max_length=100, choices=FLOOR, blank=True, null=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('username',) objects = CustomUserManager() def __str__(self): return self.get_full_name() or self.username Here's the relevant part of the traceback: from events.models import EventVenue File "C:\Users\SAIF\Desktop\projects\bgv\bgv\events\models.py", line 17, in <module> from cms.models.fields import PlaceholderField File "C:\Users\SAIF\Anaconda3\envs\bgv\lib\site-packages\cms\models\__init__.py", line 3, in <module> from .permissionmodels import * # nopyflakes File "C:\Users\SAIF\Anaconda3\envs\bgv\lib\site-packages\cms\models\permissionmodels.py", line 19, in <module> User = apps.get_registered_model(user_app_name, user_model_name) File "C:\Users\SAIF\Anaconda3\envs\bgv\lib\site-packages\django\apps\registry.py", line 273, in get_registered_model raise LookupError( LookupError: Model 'accounts.CustomUser' not registered. i have tried to change the app order in the INSTALLED_APPS and inherit from the `PermissionsMixin` in … -
Multithreaded Script Does not Increment Order Number Properly for a Django Database Entry
I have an images endpoint like this: /api/properties/image/ and I can post an image to the endpoint, and that saves an image link to the Postgres database. This line of code handles the logic: def create(self, validated_data): property_id = self.context['property_ad_id'] # This line handles the update order = PropertyImage.objects.filter(ad_id=property_id).count() + 1 return PropertyImage.objects.create(ad_id=property_id, order=order, **validated_data) From the above, it counts how many images are currently in the database, stores it in memory then increments it by one, and finally, it creates a new image with that incremented value as its order. The operation works as intended until I use a multithreaded script as the one below to mass-populate the images: def single_property_upload(image_file, property_id): BASE_URL_PROPERTY = base(property_id=property_id) with image_file.open(mode="rb") as f: image_data = f.read() files_data = {"image": ("image.jpg", image_data, "image/jpeg")} response = requests.post(BASE_URL_PROPERTY, files=files_data) def post_images(image_files, id): threads = [] for image_file in image_files: # Create a new thread for each image upload t = threading.Thread(target=single_property_upload, args=(image_file, id)) t.start() threads.append(t) # Wait for all threads to complete for t in threads: t.join() def populate_images(): for i in range(1, 1001): image_files = [ Path.cwd() / "house_images2" / f"{str(randint(1, 160))}.jpg" for i in range(4) ] post_images(image_files, str(i)) print(f"Property {i} populated successfully") print("Done") populate_images() … -
Solving the Django Testing Puzzle: Incorporating JWT Tokens in Authorization for POST
I'm encountering an issue while testing a Django REST Framework endpoint that requires authentication and authorization using the IsAdminUser permission class. The endpoint is designed to handle POST requests, and it checks if the authenticated user has the is_admin attribute set to True. Here's a simplified version of the endpoint code: class MyView(APIView): permission_classes = (IsAdminUser,) def post(self, request): master = request.user if master.is_admin: name = request.data['name'] I have written a test case to simulate a POST request to this endpoint, and I'm encountering the error 'AnonymousUser' object has no attribute 'is_admin' when I run the test case with the following code: class MyViewTestCase(TestCase): def setUp(self): self.client = APIClient() token = '{jwt_token}' client.credentials(HTTP_AUTHORIZATION="token " + token) self.valid_data = {"name": "A", "at": "11", "d": "11"} def test_valid_request(self): client = APIClient() response = client.post('/endpoint', self.valid_data, format='json') I have confirmed that the endpoint works correctly when tested with an authorization token in Postman. How can I properly authenticate the user in my test case to avoid this error and successfully test the authenticated endpoint? Any insights or examples on how to structure the test case for a token-authenticated POST request with the IsAdminUser permission would be greatly appreciated! -
Error Encountered When Pushing Code with Azure AD (MSAL) Integration to Azure Web App Using GitHub
I have a Django project with a built-in authentication system that works fine in both development (dev), system integration testing (SIT), and production (PROD) environments. After implementing Azure AD integration and starting the server with "sslserver," everything works fine because Django runs on HTTPS. However, when I push the code to the production environment, I encounter an error: "Application error." I encountered multiple issues during the implementation: When running the Django server using "runserver," I encountered an error: AADSTS50011: The redirect URI 'http://domain.azurewebsites.net/auth/redirect' specified in the request does not match the redirect URIs configured for the application. I identified this problem when using the sign-in feature, as it failed to authenticate and pick up the correct redirect URI. After changing the redirect URI from HTTP to HTTPS, the sign-in authentication was successful. However, when Azure AD sent a response to the Django app, another error occurred: You are trying to access "http://domain.azurewebsites.net/auth/redirect," but the return URI is "http://domain.azurewebsites.net/auth/redirect." [30/Nov/2023 11:46:33] Code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x02\x1a\x01\x00\x02\x16\x03\x03M\x12Â;Fþæw') [30/Nov/2023 11:46:33] You're accessing the development server over HTTPS, but it only supports HTTP. This issue arises when the Django project runs on HTTP. Switching to HTTPS might resolve the problem. So, … -
dropdown select showing up in views.py but not in the clean method in forms.py
I have a django template as follows <div class="container-fluid lineitem_form_container"> <div class="inner_holder"> <h2>Add Line Item</h2> <form method="post" action="{% url 'Dashboard:lineitems' %}" class="col-md-6"> {% csrf_token %} {{ form.non_field_errors }} <div class="mb-3"> <label for="{{ form.name.id_for_label }}" class="form-label">Line Item Name:</label> {{ form.name }} </div> <div class="mb-3"> <label for="{{ form.category.id_for_label }}" class="form-label">Category:</label> {{ form.category }} {{ form.new_category }} </div> <div class="mb-3"> <label for="{{ form.segment.id_for_label }}" class="form-label">Segment:</label> {{ form.segment }} {{ form.new_segment }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <script> // JavaScript code to toggle visibility of new category/segment fields document.addEventListener('DOMContentLoaded', function () { var categoryDropdown = document.querySelector('#id_category'); var newCategoryField = document.querySelector('#id_new_category'); var segmentDropdown = document.querySelector('#id_segment'); var newSegmentField = document.querySelector('#id_new_segment'); // Initial state newCategoryField.style.display = 'none'; newSegmentField.style.display = 'none'; categoryDropdown.addEventListener('change', function () { newCategoryField.style.display = categoryDropdown.value === 'new_category' ? 'block' : 'none'; }); segmentDropdown.addEventListener('change', function () { newSegmentField.style.display = segmentDropdown.value === 'new_segment' ? 'block' : 'none'; }); }); </script> </div> This is my forms.py class CustomTextInput(TextInput): def __init__(self, *args, **kwargs): kwargs['attrs'] = {'class': 'form-control'} super().__init__(*args, **kwargs) class LineItemForm(forms.ModelForm): new_category = forms.CharField( max_length=255, required=False, label='New Category', widget=CustomTextInput(attrs={'class': 'form-control', 'placeholder': 'Enter new category'}), ) new_segment = forms.CharField( max_length=255, required=False, label='New Segment', widget=CustomTextInput(attrs={'class': 'form-control', 'placeholder': 'Enter new segment'}), ) class Meta: model = LineItem fields = ['name', … -
Encryption in react and Decryption in django
i'm building a authentication system using react and django, Now i have a problem i want to encrypt password in UI then send it to backend, but i don't know how to decrypt it back in django I used crypto js in frontend. const VITE_PASSWORD_KEY = import.meta.env.VITE_PASSWORD_KEY; export function EncryptString(data){ var enc_string= CryptoAES.encrypt(data,VITE_PASSWORD_KEY ).toString(); return enc_string; } so now i encrypted like this and send it to server/backend now how can i handle it in backend?? -
I have django app and also have a function for arrange data of excel file i create in this want to pick file path from url
views.py def upload_file(request): if request.method == 'POST': try: excel_file = request.FILES.get('file') file_data = excel_file.cleaned_data['file'].read() file_name = excel_file.cleaned_data['file'].name file = default_storage.save(file_name, ContentFile(file_data)) xlxs = process_file(file, process_type='json', db_type='default') if xlxs: return HttpResponse(f'File path: {xlxs}') else: return HttpResponse("There was an error during the process.") except Exception as e: # Print the exception for debugging print(f"Error in process_file: {e}") return HttpResponse("An unexpected error occurred during the process.") i want to resolve this from a library -
Django migrations does not apply in production
I'm running a django rest api inside a docker container on my local machine. I modified a model, commited the migrations and rebuild the container with docker-compose. The changes are applied correctly. Therefore, I pulled the repository on the deployement server, and proceed to rebuild the containers. However, the migrations are not reflected inside the database. Do you have any idea why, and how I could apply my changes ? Here is my entrypoint for my django container. #!/bin/bash ### WAITING POSTGRES START ### RETRIES=7docker exec -it <your_backend_container_name> python manage.py showmigrations host="postgis" while [ "$RETRIES" -gt 0 ]; do echo "Waiting for postgres server, $((RETRIES--)) remaining attempts..." PG_STATUS="$(pg_isready -h $host -U postgres)" PG_EXIT=$(echo $?) echo "Postgres Status: $PG_EXIT - $PG_STATUS" if [ "$PG_EXIT" = "0" ]; then RETRIES=0 else sleep 5 # timeout for new loop fi done # run command from CMD python manage.py makemigrations python manage.py migrate exec "$@" I tried to log into the psql container, and look manually if the modification were present. They are not. I also tried to log in into the django container and to reapply the mgirations, and it does not change anything. -
python subprocess getting error when trying to install requirements.txt
I am trying to develop an automate python scripts using python subprocess. I am using fastapi uvicorn server for build automatically djago project but got internal 500 server error fast api while installing requirements.txt for django project. I am using python 3.11 my code @app.post("/webhook") async def webhook(request: Request): try: repo_directory = 'D:/web development/ScratchFb' python_directory = 'D:/web development/ScratchFb/fbscratch/backendfb' nextjs_directory = 'D:/web development/ScratchFb/fbscratch/fontendfb' #clone git repo clone_command = subprocess.run(['git', 'clone', 'https://github_url'], cwd=repo_directory,check=True) # create virtual environment python vertual_venv = subprocess.run(['python', '-m', 'venv', 'venv'], cwd=python_directory ,check=True) # Activate the virtual environment based on the platform if sys.platform == 'win32': activate_venv = subprocess.run(['venv\\Scripts\\activate'], cwd=python_directory , shell=True, check=True) else: activate_venv = subprocess.run(['source', 'venv/bin/activate'], cwd=python_directory, shell=True, check=True) #installing requirements.txt install_req_txt = subprocess.run(['pip', 'install', '-r', 'requirements.txt'], cwd=python_directory,check=True) #install npm npm_i = subprocess.run(['npm', 'i'], cwd=nextjs_directory,check=True) # Check the exit code of npm_i before proceeding to npm_build if npm_i.returncode == 0: # Run build command if npm install was successful npm_build = subprocess.run(['npm', 'run', 'build'], cwd=nextjs_directory, check=True) else: print("Error: npm install failed.") here error { "error": "Command '['pip', 'install', '-r', 'requirements.txt']' returned non-zero exit status 1." } -
Passenger error #3 when installing django application in DirectAdmin host
When i was installed django app in DirectAdmin, i found error like this in when i go to my domain enter image description here, how to fix that? i've tried finding solution, but there is just solution to fixing to root file -
Pass variable through HttpResponse | Django
I have the following code working properly to download a file @ Django: def download_file(request): response = HttpResponse(Document2.file, content_type='application/force-download') response['Content-Disposition'] = f'attachment; filename="sigma.xlsx"' return response My goal: after the user has downloaded the file, in other words, the def download_file has been runned, I need to show the form in the template page. <h2><i class="fa fa-cog"></i></h2> <h1>Upload base de dados</h1> <p>Antes de realizar o upload da nova base de dados, realize, por medidas de segurança, <span class="detail-color">o download</span> do atual banco de dados.</p> <br> <a href="{% url 'auditoria_app:download_file' %}" class="" style="color: red">Clique aqui para baixar o arquivo atual.</a> **{% if variable = 'yes' %}** <form id="" action="{% url 'auditoria_app:upload' %}" method="POST" class="" enctype="multipart/form-data"> {% csrf_token %} <label for="test"> <section><i class="fas fa-cloud-upload-alt fa-3x"></i> Clique aqui ou arraste a base de dados para essa área!</section> {{ form.as_p }} </label> <p id="filename"></p> <button type="submit" class="button-section-1" onclick="disable()" value="Save"> Iniciar upload </button> </form> **{% endif %}** As a precautionary measure, I would like the user to download the file before uploading a new one. Hence the reason for rendering the page only after the download has been completed. How can I solve this? Tks! -
Hello guys,pls can help me:(staticfiles.W004) The Directory /Users/jcu/Desktop/work/webserver/static in the STATICFILES_DIRS setting does not exist
and so, I'm just interning and learning everything right now, I need to make sure that there is an input your name field and when entering the name it gives Hello,"name",I did it initially using js+node+webpack, but now I need to transfer it to Django, I have already entered and connected css files,but for some reason an error occurred with the js file I watched a lot of videos and guides, I set all the settings correctly and seemed to indicate the correct path to the folders, as well as the folders themselves are correctly arranged, but still nothing happens when you enter the name and click on the button and there is such an error in the console,if you need to throw off the code, please tell me about it, can there also be a problem that I connected css and js in the same HTML file? -
Visual Studio Django - Freezes on python manage.py createsuperuser
So, I'm new to Django and am using Visual Studio 2022 with Python 3.12 (which is apparently not fully supported by Visual Studio). When I start a fresh Django web app project, it prompts for me to create a super user. Doing so, it freezes (without any error message) as it executes "manage.py createsuperuser" (as shown in screenshot). Any suggestions? -
Issue with Swagger representation of geographical coordinates in Django using DRF and drf-yasg
I am facing an issue with Swagger representation for geographical coordinates in my Django project. I'm using Django Rest Framework (DRF) along with drf-yasg for API documentation. I have a model named Facility with a field coordinates representing geographical coordinates in the Point format. To handle this, I'm using the GeoFeatureModelSerializer from DRF-GIS and a custom serializer PointSerializer for proper representation. However, the Swagger documentation is not correctly displaying the coordinates. I suspect there might be an issue with how Swagger processes geographical data. Here are relevant code snippets: # models.py from django.contrib.gis.db import models class Facility(models.Model): coordinates = models.PointField() # serializers.py from rest_framework_gis.serializers import GeoFeatureModelSerializer from django.contrib.gis.geos import Point from drf_yasg.utils import swagger_serializer_method class PointSerializer(serializers.BaseSerializer): def to_representation(self, instance): if isinstance(instance, Point): return { 'type': 'Point', 'coordinates': [instance.x, instance.y], } def to_internal_value(self, data): if data['type'] == 'Point': coordinates = data['coordinates'] # Your coordinate validation here return Point(coordinates[0], coordinates[1]) @swagger_serializer_method(serializer_or_field=Point) def to_swagger_object(self, value): return { 'type': 'Point', 'coordinates': [value.x, value.y], } class FacilitySerializer(GeoFeatureModelSerializer): coordinates = PointSerializer() class Meta: model = Facility geo_field = 'coordinates' fields = '__all__' depth = 1 I implemented a custom PointSerializer with DRF-GIS's GeoFeatureModelSerializer in Django to handle geographical coordinates. The serializer works in regular API responses, … -
python: can't open file 'manage.py': [Errno 2] No such file or directory (Docker-compose)
when i tryna run a django server with docker-compose up, i got this error [+] Running 2/2 ✔ Network service_default Created 0.3s ✔ Container service-web-app-1 Created 0.5s Attaching to service-web-app-1 service-web-app-1 | python3: can't open file 'manage.py': [Errno 2] No such file or directory service-web-app-1 exited with code 2 My docker-compose version: "3.9" services: # postgres: # image: postgres:15 # container_name: dj_post # env_file: # - .env web-app: build: dockerfile: ./Dockerfile context: . ports: - '8000:8000' command: > sh -c "python3 manage.py runserver " My Dockerfile FROM python:3.8-alpine3.16 COPY requirements.txt /temp/requirements.txt WORKDIR /service EXPOSE 8000 RUN pip install -r /temp/requirements.txt RUN adduser --disabled-password service-user USER service-user I will attach the architecture of the folders below, but I immediately say that by setting the full path to manage.py in docker-compose file I get the same error,I just started studying docker and for two days I can't find a working solution to this problem,share your ideas:( -
Get a dictionary of related model values
I have a model Post with some fields. Aside from that I have some models which have Post as a ForeignKey. Some examples are: class ViewType(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="view_types", verbose_name=_("Post"), ) view = models.CharField( max_length=20, choices=VIEW_TYPE_CHOICES, verbose_name=_("View") ) ... class HeatType(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="heat_types", verbose_name=_("Post"), ) heat = models.CharField( max_length=30, choices=HEAT_TYPE_CHOICES, verbose_name=_("Heat") ) ... So what I want to do here is somehow get a dictionary with all the values of those fields in my view. For example instead of doing this for all of the models that have Post as a ForeignKey: heat_type = HeatType.objects.filter(post=post) view_type = ViewType.objects.filter(post=post) dict = { "view_type": view_type.view, "heat_type": heat_type.heat, etc... } get all the relevant related fields in one go. Is there a simpler solution for that? Or do I have to manually get all queries for each model? Thanks in advance -
VS Code debugger not working (by using launch.json) for a django project
I am having trouble using the debugger in VS code. This is my first time using VS code and I'm following a Django tutorial from VS code (https://code.visualstudio.com/docs/python/tutorial-django). By the section 'explore the debugger' I got stuck, because my debugger doesn't seem to work (probably because I did something stupid or didn't do something). The thing is, I don't get an error message or something but it just keeps running. As the status bar in VS code doesn't change in the color orange, see image (which it should according to the tutorial). Statusbar while debugging My debugger also doesn't seem to stop at the breakpoint, that I have set at line 9.enter image description here. And here it just keeps running enter image description here I tried stopping the debugger and trying it again, but the outcome doesn't change. -
AttributeError: 'Logger' object has no attribute 'warn'
I'm trying to connect celery to my django project via docker. But when starting the worker container, I get the following error - File "/usr/local/lib/python3.13/site-packages/kombu/transport/redis.py", line 92, in <module> crit, warn = logger.critical, logger.warn ^^^^^^^^^^^ AttributeError: 'Logger' object has no attribute 'warn' My requirements.txt file: Django==4.2.7 psycopg==3.1.13 celery[redis]==5.3.6 django-celery-beat==2.5.0 redis==5.0.1 My dockerfile: FROM python:3.13.0a1-alpine3.18 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements /temp/requirements RUN apk add postgresql-client build-base postgresql-dev RUN pip install -r /temp/requirements/local.txt WORKDIR /myproject COPY . . EXPOSE 8000 My docker-compose.yml: redis: image: redis:7.2.3-alpine3.18 ports: - '6379:6379' restart: always worker: build: context: . command: > sh -c "celery -A config worker -l INFO" restart: always depends_on: - redis Structure of my project: The src folder contains apps. I tried to solve this problem but I failed. Please tell me what the problem might be and how to solve it. Thank you! -
How can I send emails from the system (admin user) to the client authenticated by oauth2 using Microsoft email and django rest framework?
I know I can do it by configuring django's sendmail, it doesn't matter if the email is gmail or outlook. However, I cannot use an email with my own provider. I need to do this authentication with oauth2, how can I do it to send emails from my own provider? I hope to send emails with any provider that implements oauth2 -
View does not contain the user which send a request
i created a view for payment verification, but after the payment, even use logged in before, it return anonymous user. how can i edit my code to include the user which send the request def verify(request, *args, **kwargs): order_id = kwargs['order_id'] open_order: Order = Order.objects.filter( Q(user=request.user.id) & Q(is_paid=False)).first() total_price = int(open_order.total_price()) t_status = request.GET.get('Status') t_authority = request.GET['Authority'] req = None if request.GET.get('Status') == 'OK': req_header = {"accept": "application/json", "content-type": "application/json'"} req_data = { "merchant_id": MERCHANT, "amount": total_price, "authority": t_authority } req = requests.post(url=ZP_API_VERIFY, data=json.dumps( req_data), headers=req_header) if len(req.json()['errors']) == 0: t_status = req.json()['data']['code'] if t_status == 100: order = Order.objects.get_queryset().get(id=order_id) order.is_paid = True order.refrence_id = req.json()['data']['ref_id'] order.authority_id = t_authority order.pay_date = datetime.now() order.save() context = { 'verification_successful': True, 'reference_id': str(req.json()['data']['ref_id']), 'orderID': order_id, } return render(request, 'eshop_cart/verify.html', context) elif t_status == 101: context = { 'verification_successful': False, } return render(request, 'eshop_cart/verify.html', context) else: context = { 'verification_successful': False, } return render(request, 'eshop_cart/verify.html', context) else: e_code = req.json()['errors']['code'] e_message = req.json()['errors']['message'] return HttpResponse(f"Error code: {e_code}, Error Message: {e_message}") else: context = { 'verification_successful': False, 'order_id': order_id, } return render(request, 'eshop_cart/verify.html', context) how can i edit this code to have user id in it, thanks for helping -
Why is this Django test opening so many database connections?
I'm testing my Django REST API using Schemathesis and Django's built-in unittest. The code for my test suite is: from contextlib import contextmanager import schemathesis from hypothesis import given, settings from hypothesis.extra.django import LiveServerTestCase as HypothesisLiveServerTestCase from my_app.api import api_v1 from my_app.tests import AuthTokenFactory # 3 requests per second - `3/s` # 100 requests per minute - `100/m` # 1000 requests per hour - `1000/h` # 10000 requests per day - `10000/d` RATE_LIMIT = "10/s" openapi_schema = api_v1.get_openapi_schema() @contextmanager def authenticated_strategy(strategy, token: str): @given(case=strategy) @settings(deadline=None) def f(case): case.call_and_validate(headers={"Authorization": f"Bearer {token}"}) yield f class TestApiSchemathesis(HypothesisLiveServerTestCase): """ Tests the REST API using Schemathesis. It does this by spinning up a live server, and then uses Schemathesis to automatically generate schema-conforming requests to the API. """ def setUp(self): super().setUp() self.schema = schemathesis.from_dict( openapi_schema, base_url=self.live_server_url, rate_limit=RATE_LIMIT ) def test_api(self): """ Loop over all API endpoints and methods, and runs property tests for each. """ auth_token = AuthTokenFactory().token for endpoint in self.schema: for method in self.schema[endpoint]: with self.subTest(endpoint=f"{method.upper()} {endpoint}"): strategy = self.schema[endpoint][method].as_strategy() with authenticated_strategy(strategy, auth_token) as run_strategy: run_strategy() This has been running in CI just fine for a while, but now that I've added some new REST endpoints, I've started getting errors like: psycopg2.OperationalError: connection … -
I need the success swa to be shown when entering the password correctly
js document.addEventListener("DOMContentLoaded", function () { const botonGuardarCambios = document.getElementById('botonGuardarCambios'); botonGuardarCambios.addEventListener('click', function() { const form = document.querySelector('form'); const formData = new FormData(form); // Mostrar el componente cuando se carga la página const passwordHelpBlock = document.getElementById('passwordHelpBlock'); passwordHelpBlock.classList.remove('d-none'); // Borrar mensajes de error al recargar la página const formErrors = document.getElementById('form-errors'); if (formErrors) { formErrors.classList.add('d-none'); } const url = `/usuarios/cambiar_password`; console.log('antes del fetch') fetch(url, { method: 'POST', body: formData, }) .then((response) => response.json()) .then((data) => { console.log(data); if (data.success) { // Mostrar el Swal después de ocultar el componente Swal.fire({ icon: 'success', title: 'Éxito', text: 'Guardado correctamente', showConfirmButton: false, timer: 1500 }).then(() => { // Recargar la página solo si la contraseña se ha cambiado correctamente location.reload(); }); } else { console.log('Error al intentar cambiar la contraseña:',error); Swal.fire({ icon: 'error', title: 'Error', text: 'No se pudo cambiar la contraseña', }); } }) .catch((error) => { console.log('Error al intentar cambiar la contraseña:', error); Swal.fire({ icon: 'error', title: 'Error', text: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', }); }); }); }); views.py def cambiar_contraseña(request): try: if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return JsonResponse({ 'success': True, }) else: # Manejar errores en el formulario for field, errors in form.errors.items(): for error in errors: … -
How do I serve my Django App in a SSH connection with limited user restrictions?
The context is the following: I'm using a SSH connection to my college's serve, on teacher's demands, in order to serve my Django application. I found out - I suppose - that by using gunicorn I can deploy my Django application. Furthermore I found out you can bind it to a specific port. When I do the following command gunicorn --bind 0.0.0.0:8000 myapp.wsgi. I proceed to my college site address, and use the port, returning 404; collegesite:8000/ What could be the problem here? Am I lacking permissions from the OS? Do I need to run gunicorn as sudo?