Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Add Multiple Files To Single Instance
enter image description here MY Problem is when i click on extension ID it should display all the audio files relegated to that ID is there any way to upload multiples files Audio Files For Single Instance enter image description here Here Is The Second Image It Showing Only One Audio File But I want to upload multiple audio files trying to create different form applying different method in model -
Failed to get Xrpl NFt history using JSON RPC request's "nft_history" method
Hello community memebers, I'm unable to get the NFT history. I tried to get the NFT history throgh the below given snippet. from django.http import JsonResponse def get_nfthistory(request): JSON_RPC_URL = "https://s.altnet.rippletest.net:51234/" if request.method != 'POST': return JsonResponse({'success': False, 'error': 'Invalid request method'}) nft_id = request.POST.get('nft_id') # Initialize JSON-RPC client client = JsonRpcClient(JSON_RPC_URL) print(client) try: response_data = client.request(NFTHistory(nft_id=nft_id)) print(response_data) return JsonResponse({'success': True, 'data': response_data}) except Exception as e: return JsonResponse({'success': False, 'error': str(e)}) I've written this django view function in order to get NFT history. I took XRPL NFT History method as reference. And, the **NFTHistory ** in the "response_data = client.request(NFTHistory(nft_id=nft_id))" is a standard class defined in the xrpl model package. Here is the class code: """ The `nft_history` method retreives a list of transactions that involved the specified NFToken. """ from dataclasses import dataclass, field from typing import Any, Optional from xrpl.models.requests.request import LookupByLedgerRequest, Request, RequestMethod from xrpl.models.required import REQUIRED from xrpl.models.utils import require_kwargs_on_init @require_kwargs_on_init @dataclass(frozen=True) class NFTHistory(Request, LookupByLedgerRequest): """ The `nft_history` method retreives a list of transactions that involved the specified NFToken. """ method: RequestMethod = field(default=RequestMethod.NFT_HISTORY, init=False) nft_id: str = REQUIRED # type: ignore """ The unique identifier of an NFToken. The request returns past transactions of … -
I am trying to pass some json data from my django web app to a server running at localhost. Works fine at localhost but fails in production
I have a server running at 127.0.0.1:16732. I am passing json data to this server from my django app: response=requests.post('http://127.0.0.1:16732/api/v2/requests', auth=auth, json=task) Works fine when I do it from my test python server on localhost. But when I try to do the same from production server, it fails & give the following error: "HTTPConnectionPool(host='localhost', port=16732): Max retries exceeded with url: /api/v2/requests (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f3e335006d0>: Failed to establish a new connection: [Errno 111] Connection refused'))" -
ValueError: Cannot assign "'827'": "Course_Content.course_outline_id" must be a "Course_Outline" instance
So in my django view i am trying to pass the outline instance but it keeps saying ValueError: Cannot assign "'827'": "Course_Content.course_outline_id" must be a "Course_Outline" instance. I already tried converting it to int. But i dont know what i am doing wrong. I already tried using outline_instance.id so it would be more specific it still does not work. views.py class UpdateCourseOutline(View): def post(self, request): outline_id = request.POST.get('outline_id', None) new_topic = request.POST.get('new_topic', None) new_week = request.POST.get('new_week', None) new_clo = request.POST.get('new_clo', None) new_course_content_data = json.loads(request.POST.get('new-course_content', '[]')) deleted_course_content_data = json.loads(request.POST.get('deleted-course_content', '[]')) new_added_course_content_data = request.POST.getlist('add-new-course_content[]') # Update Course_Outline details outline = get_object_or_404(Course_Outline, id=outline_id) outline.topic = new_topic outline.week = new_week outline.course_learning_outcomes = new_clo outline.save() print("outline - type(outline_id):", type(outline_id)) # Add new Course_Content items self.add_course_content(int(outline_id), new_added_course_content_data) # Update Course_Content details self.update_course_content(outline_id, new_course_content_data) # Delete Course_Content items self.delete_course_content(deleted_course_content_data) # Retrieve the updated outline with course content updated_outline = Course_Outline.objects.values('id', 'topic', 'week', 'course_learning_outcomes').get(id=outline_id) updated_outline['course_content'] = list(Course_Content.objects.filter(course_outline_id=outline_id).values('id', 'course_content')) data = { 'success': True, 'message': 'Course outline updated successfully!', 'outline_id': updated_outline['id'], 'topic': updated_outline['topic'], 'week': updated_outline['week'], 'course_learning_outcomes': updated_outline['course_learning_outcomes'], 'course_content': updated_outline['course_content'], # Add other fields if needed } return JsonResponse(data) def add_course_content(self, outline_id, new_values): try: # Get the Course_Outline instance based on the outline_id outline_instance = get_object_or_404(Course_Outline, id=outline_id) # Log information … -
How to run an application automatically and in the background in Django?
I have an application that displays on a page a stream from a video camera on which detections are indicated. I need to count them for further statistics. The problem is that all the script logic only works if I open a specific page. That is, I opened the “Camera1” page, saw the video stream from it and the script detects and counts the objects in the frame. If I open "Camera2" - the same. I need these scripts to work even when the page is not open. That is, for example, after rebooting the server, the Django application is automatically launched and, as it were, the opening of all pages from the cameras is simulated so that the scripts start working. In a word, I need the script to work even if it is not called directly on the page. Is this possible and if so - how? Thank you -
Kerberos Implementation in Django
How do i implement an Kerberos SSO in Django? I am new to Django and need something like a Documentation or Tutorial on how to integrate KErberos and LDAP as SSO in a Django app. I've searched now for a long time and did not find any complete or reasonable solution. -
Django AWS Elastic Beanstalk - 502 Bad Gateway
I have been trawling the internet looking for a solution to this problem and have come up empty handed after trying multiple different things. Im looking to get the vanilla django project deployed on AWS EB. I am new to this so I am sure there is something simple that I am missing. I followed this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html as well as many other YouTube / Stack tutorials and posts hoping to get around this 502 error. Here is my setup. project setup This is my django.config file: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application Here is my config.yml file: branch-defaults: default: environment: django-env2 group_suffix: null global: application_name: django-tut branch: null default_ec2_keyname: null default_platform: Python 3.9 default_region: us-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application In Settings.py the only change I made was: ALLOWED_HOSTS = ['django-env2.eba-wftrfqr2.us-west-2.elasticbeanstalk.com'] This is requirements.txt asgiref==3.7.2 Django==3.1.3 pytz==2023.3.post1 sqlparse==0.4.4 typing_extensions==4.8.0 When I run the server locally it works perfectly, giving the generic django page on http://127.0.0.1:8000/ (this is before I update ALLOWED_HOSTS of course). In console its status turns to "Severe" and a warning event is displayed: "Environment health has transitioned from Pending to Severe. ELB processes are not healthy on … -
Content security policy(CSP) in django Project
We need to implement content security policy(CSP) in our Django project, I am not able to apply CSP in inline style and inline script, Please suggest any solution? We are using nonce and hashes for validation inline script and inline style, Nonce is working in tag, but not working in tag & inline style. please suggest any solution. -
"django-admin is not recognized as internal or external command"
I have installed django, but still it shows "django-admin is not recognized as internal or external command". installed the updated version but shows me the same error. I am trying to build a project using django. I have tried to install django everytime I opened prompt and couldn't move past this problem. I need a solution to solve this problem -
How do I create an Instagram login and registration page in Django? [closed]
How do I create an Instagram login and registration page in Django? I searched a little on the internet, the information tired me, so I didn't get a good result. Can you help me with some code and explanation? I want to add a feature to log in and record Instagram in Django. -
AttributeError with django
I am trying to build an api that uses a chatbot that I built. I have the chatbot and other needed classes in a separate file called functions.py. In my views.py I import these classes and get this error: Traceback (most recent call last): File "/home/dude/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/dude/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dude/.local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/home/dude/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/home/dude/Desktop/Projects/Finance Webapp/Financial_Chatbot_API/chatbot/views.py", line 36, in chatbotRequestHandler chatbotObj = ChatBot() File "/home/dude/Desktop/Projects/Finance Webapp/Financial_Chatbot_API/chatbot/functions.py", line 104, in __init__ self.vectorizer = load(file) AttributeError: Can't get attribute 'custom_preprocessor' on <module '__main__' from '/home/dude/Desktop/Projects/Finance Webapp/Financial_Chatbot_API/manage.py'> This is how i'm importing these classes: from .functions import StockGrab, ChatBot, custom_preprocessor I have tried adding the custom_preprocessor into the import but that did not work. Any other Ideas? -
How can I read a PDF file that is saved in the media folder in Django? I want to display it on an HTML page according to each id
I have developed a function within the views.py file. I made a for loop on that html page, but only this PDF file is the issue. The name, ID number, and other details all function flawlessly. {% for i in prid %} <tr> <td>{{i.id}}</td> <td>{{i.help_name}}</td> <td>{{i.help_service}}</td> <td>{{i.help_budget}}</td> <td><a href="/pdfview/" target="_blank" type="application/pdf" height="50px" width="20px">view file</a></td> <td>{{i.help_message}}</td> <td style="font-weight: bold;">{{i.help_status}}</td> <td id="click" ><a href="/adminprojectsurvey/?surveyid={{i.id}}"> click to survey</a></td> </tr> {% endfor %} #in views.py def admin_project(request): if request.method == 'GET': add = helpingtable.objects.all() return render(request,'admin/project.html',{'prid':add}) else: return render(request,'admin/index.html') these are my code, -
I cant install my mysqlclient in my machine. What should I do?
Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [46 lines of output] # Options for building extention module: library_dirs: ['C:/mariadb-connector\lib\mariadb', 'C:/mariadb-connector\lib'] libraries: ['kernel32', 'advapi32', 'wsock32', 'shlwapi', 'Ws2_32', 'crypt32', 'secur32', 'bcrypt', 'mariadbclient'] extra_link_args: ['/MANIFEST'] include_dirs: ['C:/mariadb-connector\include\mariadb', 'C:/mariadb-connector\include'] extra_objects: [] define_macros: [('version_info', (2, 2, 0, 'final', 0)), ('version', '2.2.0')] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\connections.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\converters.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\cursors.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\release.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\times.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb_exceptions.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb creating build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CR.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\ER.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FLAG.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants running egg_info writing src\mysqlclient.egg-info\PKG-INFO writing dependency_links to src\mysqlclient.egg-info\dependency_links.txt writing top-level names to src\mysqlclient.egg-info\top_level.txt reading manifest file 'src\mysqlclient.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' adding license file 'LICENSE' writing manifest file 'src\mysqlclient.egg-info\SOURCES.txt' copying src\MySQLdb_mysql.c -> build\lib.win-amd64-cpython-312\MySQLdb running build_ext building … -
Joining same group, but get only own data?
Is it possible to implement a Django Channels application where multiple users are connected to the same group, but each user only receives their own related data? -
¿Como puedo hacer para que el usuario al iniciar sesion y vuelva hacia atras no vuelva al formulario de login si no al index?
Actualmente me encuentro desarrollando una pagina web con Django y resulta que quiero que al usuario iniciar sesión no pueda volver al formulario de log in, tengo ese problema intenté varias formas y todas me salían erróneas, me gustaría que me pudieran ayudar o dejar alguna documentación a la cual poder ingresar y estudiar, yo creo y es lo más probable es que tuve algún error en el código o no supe donde implementarlo. Como hacer para que el usuario al iniciar sesion y vuelva hacia atras no vuelva al formulario de login si no al index -
Razorpay Subscription
Multiple orders, getting created one with 'paid' status and another one 'created' status, and the subscription is not getting activated. I am able to create the subscription in Razor pay, but the problem is that double orders are being created in Razor pay, one of which has the status of paid and the latest order has the status of created and the subscription is not getting activated after creation. views.py @login_required def process_payment(request, membership_id): membership = get_object_or_404(Membership, id=membership_id) amount = membership.price * 100 # Amount in paise if request.method == 'POST': # Process the payment data = request.POST razorpay_order_id = data['razorpay_order_id'] razorpay_payment_id = data['razorpay_payment_id'] # Update the UserMembership with the new membership user_membership = UserMembership.objects.get(user=request.user) user_membership.membership = membership user_membership.save() messages.success(request, 'Payment successful!') return render(request, 'membership/payment_success.html') else: # Create a Razorpay order order = razorpay_client.order.create({ 'amount': amount, 'currency': 'INR', 'payment_capture': '1' }) return render(request, 'membership/process_payment.html', {'order': order, 'membership': membership, 'razorpay_key': settings.RAZORPAY_KEY}) @csrf_exempt def payment_success(request): if request.method == 'POST': print(request.method) data = request.POST razorpay_order_id = data['razorpay_order_id'] razorpay_payment_id = data['razorpay_payment_id'] # Retrieve the membership associated with the Razorpay order membership_id = int(data['membership_id']) membership = Membership.objects.get(id=membership_id) # Update or create a Subscription record user_membership = UserMembership.objects.get(user=request.user) subscribe, created = LocalSubscription.objects.get_or_create(user_membership=user_membership) response = razorpay_client.payment.fetch(razorpay_payment_id) payment_status … -
How do I manipulate a Django dictionary in JavaScript?
I have a dictionary called cards, which I have created from my Card model. Each card has a front and back property. I think I am importing the 'cards' dictionary into my JS file from the template correctly. But I am unsure on how to access the vales from the dictionary, and how to display the values without any {,[,' etc. I did previously try having 2 different arrays: one for the fronts of the cards, one of the backs of the cards. However, I have a feeling this could get messy later on. Either way, it would be useful to know how to display python dictionaries in JS. models.py: from django.db import models class Deck(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Card(models.Model): front = models.CharField(max_length=200) back = models.CharField(max_length=200) deck = models.ForeignKey(Deck, on_delete=models.CASCADE, related_name='cards') def __str__(self): return self.front view function: def learn(request, deck_id): deck = get_object_or_404(Deck, pk=deck_id) cards_queryset = deck.cards.all() cards = [{'front': card.front, 'back': card.back} for card in cards_queryset] return render(request, 'srs/learn.html', { 'deck': deck, 'cards': cards, }) template file: {% extends "srs/layout.html" %} {% load static %} {% block body %} <div class="body-container"> <p class="front"></p> <p class="back"></p> <button id="show-answer">Show Answer</button> <button id="next-card">Next</button> </div> <div id="cards-var" data-cards="{{ … -
How to configure celery with SQS as backend?
I'm trying to setup a SQS broker with a celery app, configured in a django project. Here's my setup: celery.py: import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") app = Celery("my-app") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() My celery related django settings: CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "eu-west-1", "queue_name_prefix": f"celery-", } CELERY_BROKER_URL = "sqs://" CELERY_TASK_DEFAULT_QUEUE = "default" This configuration works fine using a rabbitmq broker, which makes me think the overall configuration is correct, but when I use SQS as broker, the messages are sent to SQS (the "Message available" counter increases), but once picked up by my worker, they go to "Messages in flight" and stay there forever it seems (at least for hours). Also, I can see the worker logs doing things, but never actually executes the task for some reason. Here are some celery worker logs: host;x-amz-date 786cb490d758593ebf5a6e0c0b34cf025b3309bb0d777891344fd32bd01cb61b [2023-11-19 19:52:05,766: DEBUG/MainProcess] StringToSign: AWS4-HMAC-SHA256 20231119T195205Z 20231119/eu-west-1/sqs/aws4_request 32a2b642b24ffcd3f42216826611c27799efb1cf756b26e7119d5553009f527c [2023-11-19 19:52:05,766: DEBUG/MainProcess] Signature: 93bcf47703548603fa0787fbbd2ae8aa4b54460db91695f4f6c818b9141b620e [2023-11-19 19:52:10,959: DEBUG/MainProcess] Response headers: {} [2023-11-19 19:52:10,960: DEBUG/MainProcess] Response body: b'<?xml version="1.0"?><ReceiveMessageResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"><ReceiveMessageResult><Message><MessageId>c4e1b404-.....-c046dc4aeb60</MessageId><ReceiptHandle>AQEBy+4G0x9BF8su10zFWJQuyEXJOFSxF........cRPUdk/vjWzirMiBw97ZSG44M=</ReceiptHandle><MD5OfBody>483202aa2938b...da1b024b63</MD5OfBody><Body>eyJib2R5IjogIlcxdGRMQ0I3...CJyZXBseV90byI6ICJmOWZjY2FmDIyMTBkYTAyMiJ9fQ==</Body><Attribute><Name>ApproximateReceiveCount</Name><Value>1</Value></Attribute></Message></ReceiveMessageResult><ResponseMetadata><RequestId>28a76707-9a01...d3f3a42ad7</RequestId></ResponseMetadata></ReceiveMessageResponse>' [2023-11-19 19:52:10,960: DEBUG/MainProcess] Event choose-signer.sqs.ReceiveMessage: calling handler <function set_operation_specific_signer at 0xffff9b901750> [2023-11-19 19:52:10,960: DEBUG/MainProcess] Calculating signature using v4 auth. [2023-11-19 19:52:10,960: DEBUG/MainProcess] CanonicalRequest: POST /ACCOUNT_ID/celery-default host:sqs.eu-west-1.amazonaws.com x-amz-date:20231119T195210Z host;x-amz-date 786cb490d758593ebf5a6e...d777891344fd32bd01cb61b [2023-11-19 19:52:10,961: DEBUG/MainProcess] StringToSign: AWS4-HMAC-SHA256 20231119T195210Z 20231119/eu-west-1/sqs/aws4_request … -
Multi-line TeX expressions with Django MathJax
I am using MathType to convert formulas to TeX notation and pass them as template variables in Django. Most formulas convert to a single line and work fine. But there are some that convert to several lines and I am struggling to figure out if it is possible to render them in the template. Working example: Formula: Django view: def mmm(request): #The formula string is the result of conversion to Tex via MathType copy-paste option mean_formula = "$$\overline x = {{\sum {{x_i}} } \over n}$$" return render( request, "statistics101/mmm.html", { "mean_formula": mean_formula, }, ) Template: <div class="formula"> <div class="formula-maths"> {{mean_formula}} </div> <div class="formula-desc"> <p> Where,<br> <b>x</b> = each value in the data set<br> <b>i</b> = the counter of the values in the data set, from 1 to n<br> <b>n</b> = the total number of values in the data set<br> </p> </div> </div> Web: Failing example: Formula: Tex conversion of the above comes out multi-line like this: $$\left( {\matrix{ n \cr x \cr } } \right){p^x}{(1 - p)^{n - x}}$$ I have tried to assign the variable in the view like this: formula = "$$\left( {\matrix{\n n \cr \n x \cr \n\n } } \right){p^x}{(1 - p)^{n - x}}$$" But on … -
Django Summernote not showing up in Linode Server
I've added Django summernote to my post model and it's working perfectly in localhost. However, the summernote field is not showing up in the server. I am using DJango+Gunicorn+Nginx in Linode. settings.py X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 urls.py path('summernote/', include('django_summernote.urls')), admin.py class BlogAdmin(SummernoteModelAdmin): # instead of ModelAdmin summernote_fields = ('content','blog_post',) admin.site.register(Blog, BlogAdmin) I am quite not sure what am I doing wrong? Localhost summernote admin summernote This is how my nginx file looks like. server { listen 80; server_name pinkgiraffemarketing.com www.pinkgiraffemarketing.com; # such as: 121.21.21.65 dev.mywebsite.com location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/pinkgiraffemarketing/staticfiles/; } location /static/admin/ { alias /home/ubuntu/pinkgiraffemarketing/venv/lib/python3.10/site-packages/django/contrib/admin/static/admin/; } location /media/ { alias /home/ubuntu/pinkgiraffemarketing/staticfiles/images/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Any guidance will be appreciated. Thank you in advance. I tried all the possible solution on the internet and none worked so far. -
Django request logs: Can't get them to appear in Cloudwatch
I'm struggling to get simple GET requests to show up in Cloudwatch. It seems that all that's appearing are some WARNING and INFO log items, not GET requests. The GET requests ARE appearing in my console when I run things locally. Here are my logging settings: cloudwatch_level = 'INFO' LOGGING_CONFIG = None logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { # exact format is not important, this is the minimum information 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s', }, "aws": { "format": "%(asctime)s [%(levelname)-8s] %(message)s [%(pathname)s:%(lineno)d]", "datefmt": "%Y-%m-%d %H:%M:%S", }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'aws', }, "watchtower": { "level": cloudwatch_level, "class": "watchtower.CloudWatchLogHandler", # From step 2 'boto3_client': boto3_logs_client, "log_group": log_group, # Different stream for each environment "stream_name": f"logs", "formatter": "aws", }, }, 'loggers': { # root logger '': { 'level': cloudwatch_level, 'handlers': ['console', 'watchtower'], }, 'django': { 'handlers': ['console', 'watchtower'], 'level': cloudwatch_level, 'propagate': True, }, 'django.server': { 'handlers': ['watchtower'], 'level': cloudwatch_level, 'propagate': True, }, "watchtower": { "level": cloudwatch_level, "handlers": ["watchtower"], "propagate": True, } } }) I'm a little confused on the logger setup for Django - should GET requests be logged by the django logger or the django.server logger? I know django.request is only for 400/500 errors, … -
Django:AttributeError: 'WSGIRequest' object has no attribute 'request'
While I want to get the clicked values from website and search the result from the database, I set up a function and create the class, when I run the server, I can read the button but while I cilck the button the mistake occured.I will show my code here. Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/search/hsa-GFAP_0019/ Django Version: 4.2.1 Python Version: 3.9.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search'] Installed Middleware: ['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'] Traceback (most recent call last): File "G:\my software\mydoc\python\pythonlist\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "G:\my software\mydoc\python\pythonlist\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\my software\mydoc\python\pythonlist\0.django_total\circRNA\search\views.py", line 70, in click_search_result return render(self.request, 'search_result.html', {'value_clicked': value_clicked, Exception Type: AttributeError at /search/hsa-GFAP_0019/ Exception Value: 'WSGIRequest' object has no attribute 'request' urls.py urlpatterns = [ path('', views.HomePageView.as_view(), name='homepage'), path('download/', views.DownloadPage.as_view(), name='download'), path('contact/', views.Contact.as_view(), name='contact'), path('search/', views.Search.as_view(), name='search'), path(r'search/?', views.Search.search_by_symbol, name='search result'), path('search/<str:value_clicked>/', views.Search.click_search_result, name='click search result') ] The urls used for click function is the last. views.py class Search(View): def get(self): return render(self.request, 'search_table.html') def search_by_symbol(self, click=None): if click is not None: symbol = click else: symbol = self.GET.get('symbol', '') if symbol: interaction1 = TestCircModels.objects.filter(symbol1__icontains=symbol) full_name_line = … -
fetch api keep saving only the first input value in django with dynamic formset, how can i make to save all the input value at once
but without using fetch api, the django save all of my input values but it keep refreshing. I need to use fetch api. please guide me through this, i am beginner! html <div> <form method="post" id="save_multiple_fields"> <h4>Choose the topic and write additional informations</h4> {% csrf_token %} <label for="id_title"></label> <select name="title" id="id_title" class="form-control"> <option value selected>------</option> <!-- {% for i in create_topic_models %} <option value="{{i.id}}">{{i}}</option> {% endfor %} --> </select> {{ select_title_form }} <br> <div class="form_list"> {{ formset.management_form }} {% for formset_form in formset %} <div class="real_form"> {{ formset_form.as_p }} </div> {% endfor %} </div> <div class="empty_form">{{ formset.empty_form.as_p }}</div> <button type="button" class="btn btn-primary" id="add_fields">add title box with textarea</button> <input type="submit" class="btn btn-primary" value="save" id="save_fields"> </form> <div id="fields_list"> </div> </div> javascript to add input fields const form_count = document.getElementsByClassName('real_form'); const id_items_TOTAL_FORMS = document.getElementById('id_items-TOTAL_FORMS') var add_fields = document.getElementById('add_fields'); add_fields.addEventListener('click',add_fields_function); function add_fields_function(event){ if(event){ event.preventDefault(); } // console.log(form_count.length) const empty_form = document.querySelector('.empty_form').cloneNode(true); const form_list = document.querySelector('.form_list'); empty_form.setAttribute('class','real_form'); empty_form.setAttribute('id',`form-${form_count.length}`) id_items_TOTAL_FORMS.setAttribute('value',form_count.length + 1); const regex = new RegExp('__prefix__','g'); empty_form.innerHTML = empty_form.innerHTML.replace(regex,form_count.length); form_list.append(empty_form); } javascript with fetch api and ignore the comments // saving multiple inputs fields document.getElementById('save_multiple_fields').addEventListener('submit',save_multiple_inputs); function save_multiple_inputs(e){ if(e){ e.preventDefault(); } const formData = new FormData(this); console.log(`---------${formData}`) fetch('{% url "jobs:createjob" %}',{ method:'POST', body: formData, }) .then(response … -
Order Django queryset by value closest to 0
I have a queryset that is returning a list of entries that are tied for the lead in a contest... leaders = ContestEntry.objects.filter(name=game, wins=wins) After I get this data I need to put them in order by a second field ('difference') as a tie breaker. The problem I can't figure out is I need the order to be by the number closest to 0. There will be a lot of negative and positive numbers. Thanks for your help -
How do I make it in a Django project so that after choosing an option in one form, the options in the other form are narrowed?
I'm trying to make my first project in Django which is a unit converter. I want to have a form where you can choose the type of units (like length, area, mass etc.). After choosing the type, then in the "to unit" and "from unit" fields there should ony be displayed units of the according type. Here are the contents of my files: models.py: from django.db import models class UnitType(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Unit(models.Model): unitType = models.ForeignKey(UnitType, on_delete = models.CASCADE) name = models.CharField(max_length=50) conversion_factor = models.DecimalField(max_digits=10, decimal_places=4) def __str__(self): return self.name def convert_to(self, value, to_unit): if isinstance(value, (int, float)) and isinstance(to_unit, Unit): conversion_factor = self.conversion_factor / to_unit.conversion_factor converted_value = round(value * conversion_factor, 4) return converted_value else: raise ValueError("Invalid input for conversion.") forms.py: from django import forms from .models import UnitType, Unit class UnitTypeForm(forms.Form): unit_type = forms.ModelChoiceField(queryset=UnitType.objects.all()) class UnitConversionForm(forms.Form): quantity = forms.DecimalField() from_unit = forms.ModelChoiceField(queryset=Unit.objects.all()) to_unit = forms.ModelChoiceField(queryset=Unit.objects.all()) def __init__ (self, unit_type, *args, **kwargs): super(UnitConversionForm, self).__init__(*args, **kwargs) self.fields["from_unit"].queryset = Unit.objects.filter(unitType_id=unit_type) self.fields["to_unit"].queryset = Unit.objects.filter(unitType_id=unit_type) views.py: from django.shortcuts import render from .forms import UnitTypeForm, UnitConversionForm from .models import UnitType, Unit def unit_converter(request, unit_type = None): if request.method == 'POST': typeForm = UnitTypeForm(request.POST) if typeForm.is_valid(): unit_type = typeForm.cleaned_data['unit_type'] form …