Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to join multiple models with OnetOne relationship in Django?
I have a main model with several fields and a few other models that serve as extra information which varies depending on user input. The main model will always be related to one of these. I want to retrieve all the information between the main models and the models with extra information. Here's an example of the relationship: class MainModel(models.Model): MAIN_MODEL_CHOICES = [(1, "Extra info 1"), (2, "Extra info 2"), (3, "Extra info 3")] name = models.CharField(max_length=100) description = models.CharField(max_length=100) choice = models.IntegerField(choices=MAIN_MODEL_CHOICES) class ExtraModel1(models.Model): main_model = models.OneToOneField(MainModel, on_delete=models.CASCADE) extra_text_info = models.TextField() class ExtraModel2(models.Model): main_model = models.OneToOneField(MainModel, on_delete=models.CASCADE) important_number = models.IntegerField() class ExtraModel3(models.Model): main_model = models.OneToOneField(MainModel, on_delete=models.CASCADE) important_bool = models.BooleanField(default=False) I have tried MainModel.objects.prefetch_related("extramodel1", "extramodel2", "extramodel3") and MainModel.objects.select_related("extramodel1__main_model", "extramodel2__main_model", "extramodel__main_model") but the retrieved queryset doesn't include the extra models, only the main one. -
Celery Tasks not Running on Mac M2 (Process 'ForkPoolWorker' exited with 'signal 11 (SIGSEGV)')
I am encountering an issue while trying to run Celery tasks on my Mac M1 machine. The error message I'm getting is as follows: The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec(). Break on __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__() to debug. [2023-11-20 15:51:19,174: ERROR/MainProcess] Process 'ForkPoolWorker-8' pid:5547 exited with 'signal 11 (SIGSEGV)' I am using Celery for my Django app task processing, and this issue seems to be related to forking on the M2 architecture. I initially attempted to resolve the issue by exporting OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES, which seemed to work for a brief period. However, the problem has resurfaced, and this solution no longer has any effect. It's worth noting that I am currently running MacOS Sonama 14.2 Beta on my machine. Interestingly, I encountered and successfully resolved this problem once before while on the same beta program. Any insights or suggestions on how to resolve this issue would be greatly appreciated. -
How to connect react native with android studio with django docker container?
I have a react native app for web configured. And I have a django app for the backend. I can connect this two apps with each other. But now I have dockerized the django app. But not the react app. And now the react app cannot any more communicate with the django docker app. So this is my docker compose.yml file: version: "3.9" name: dwl_backend services: app: image: crdierenwelzijn2.azurecr.io/web1 build: context: C:\repos\dierenwelzijn\dwl_backend dockerfile: Dockerfile args: DEV: "true" command: - sh - -c - "python manage.py wait_for_db && python ./manage.py migrate && python ./manage.py runserver 0:8000" depends_on: db: condition: service_started required: true environment: DB-PORT: "5432" DB_HOST: db DB_NAME: name DB_PASS: pass DB_USER: user DEBUG: "1" DJANGO_ALLOWED_HOSTS: localhost 127.0.0.1 [::1] SECRET_KEY: django-insecure-kwuz7%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u networks: default: null ports: - mode: ingress target: 8000 published: "8000" protocol: tcp volumes: - type: bind source: C:\repos\dierenwelzijn\dwl_backend\DierenWelzijn target: /app bind: create_host_path: true db: environment: POSTGRES_DB: db POSTGRES_PASSWORD: password POSTGRES_USER: user image: postgres:13-alpine networks: default: null volumes: - type: volume source: dev-db-data target: /var/lib/postgresql/data volume: {} networks: default: name: dwl_backend_default volumes: dev-db-data: name: dwl_backend_dev-db-data and my login method for react looks like: export const loginRequest = async (email, password) => { try { const response = await fetch("http://192.168.1.135:8000/api/user/token/", { … -
Notifications not showing on list
I have a django app with django-notifications-hq installed. The notifications are working pretty well except for the list of notifications aren't showing on the field. The notifications count is showing in the navbar. Here's my code : <div class="dropdown"> <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bell" viewBox="0 0 16 16"> <path d="M8 16a2 2 0 0 0 2-2H6a2 2 0 0 0 2 2zM8 1.918l-.797.161A4.002 4.002 0 0 0 4 6c0 .628-.134 2.197-.459 3.742-.16.767-.376 1.566-.663 2.258h10.244c-.287-.692-.502-1.49-.663-2.258C12.134 8.197 12 6.628 12 6a4.002 4.002 0 0 0-3.203-3.92L8 1.917zM14.22 12c.223.447.481.801.78 1H1c.299-.199.557-.553.78-1C2.68 10.2 3 6.88 3 6c0-2.42 1.72-4.44 4.005-4.901a1 1 0 1 1 1.99 0A5.002 5.002 0 0 1 13 6c0 .88.32 4.2 1.22 6z"/> </svg> {{ request.user.notifications.unread.count }} </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1"> {% for notification in notifications %} <a class="dropdown-item" href="{{ notification.data.action_object.get_absolute_url }}"> Notification: {{ notification.actor }} {{ notification.verb }} </a> {% empty %} <span class="dropdown-item">No notifications</span> {% endfor %} </div> </div> I've tried to consult ChatGPT but don't get any answers. So any help from this community would be a great one. Also, if you need me to post anything else, I would definitely post it here. -
Django does not load the maps in the admin panel
I need to upgrade the Django version of a project that uses GeoModelAdmin for displaying maps in the admin panel. The recommended class to be used is ModelAdmin as stated in the documentation: Deprecated since version 4.0: This class is deprecated. Use ModelAdmin instead. However, when I use ModelAdmin the maps do not load at all. And I get this error in the console: GET https://gitc.earthdata.nasa.gov/wmts/epsg3857/best/BlueMarble_ShadedRelief_Bathymetry/default/%7BTime%7D/GoogleMapsCompatible_Level8/8/92/146.jpg 500 (Internal Server Error) Is there a configuration that I missed or there are problems with the server? In the past I used OSMGeoAdmin which was exactly what I needed, but got it deprecated in Django 4.0. Now is suggested to use GISModelAdmin instead. When I use GISModelAdmin the maps are loaded, but I want to configure the zoom level and if I set the gis_widget_kwargs according to the documentation, nothing changes. gis_widget_kwargs = { "attrs": { "default_lon": 5, "default_lat": 47, "default_zoom": 3, } } -
Django .initial attribute in the form seems doesn't work
I have a problem with my Django project. I have a Model "Fattura" and a Form "EntrataForm", here is the code of the model: class Fattura(models.Model): TIPO_CHOICES = [ ('T', 'Tasse'), ('B', 'Burocrazia'), ('C', 'Clienti'), ('S', 'Spese'), ] numero = models.CharField(max_length=20) data = models.DateField(default=django.utils.timezone.now) tipo = models.CharField(max_length=1, choices=TIPO_CHOICES) importo = models.DecimalField(max_digits=10, decimal_places=2) cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE, null=True, blank=True) viaggi = models.ManyToManyField(Viaggio) def clean(self): if self.importo is None: raise ValidationError('L\'importo non può essere None.') def __str__(self): return f"{self.numero} - {self.data} - {self.importo} - {self.tipo}" and the form: class EntrataForm(forms.ModelForm): class Meta: model = Fattura fields = ['numero', 'data', 'cliente','viaggi','importo','tipo'] def __init__(self, *args, **kwargs): id = kwargs.pop('id',None) super(EntrataForm, self).__init__(*args, **kwargs) importo_finale = 0 viaggi = Viaggio.objects.filter(cliente_id=id) for viaggio in viaggi: importo_finale += viaggio.prezzo_viaggio print(id) self.fields['tipo'].widget.attrs['readonly'] = True self.fields['tipo'].required = False self.fields['tipo'].widget = forms.HiddenInput() self.fields['tipo'].initial = 'C' self.fields['viaggi'].widget.attrs['readonly'] = True self.fields['viaggi'].required = False self.fields['viaggi'].widget = forms.HiddenInput() self.fields['viaggi'].initial = viaggi self.fields['cliente'].widget.attrs['readonly'] = True self.fields['cliente'].required = False self.fields['cliente'].widget = forms.HiddenInput() self.fields['cliente'].initial = Cliente.objects.get(id=id) self.fields['importo'].widget.attrs['readonly'] = True self.fields['importo'].required = False self.fields['importo'].widget = forms.HiddenInput() self.fields['importo'].initial = importo_finale print(self.fields['importo'].initial) As you can see i use the ".initial" attribute for 4 fields, but only "importo" doesn't initialize correctly. In init the final value is correct and the last line … -
Allow Admin user to see only the user the admin creates in Django
I am trying to create a school management system, where by a school can register and becomes an admin, the school which is an admin, can create their staffs and students. The staff and students should be able to login to their accounts. The key thing here is that, there will be more than one school registered, thus each school should only see their own staffs and students. How can i ensure that the admin only sees the students and staff account created by that admin alone? Functionality so far I have created different user type accounts, admin(school) can login and create a student and staff accounts, students and staffs account created by admin which is the school can also login. The thing here is that, all admin can see all staffs, i don't want this to happen, i want admin to only see the student and staffs created by that admin alone. Below is my code for review accounts/models.py my custom user model class CustomUser(AbstractUser): USER_TYPE = ((1, "school"), (2, "Staff"), (3, "Student")) GENDER = [("M", "Male"), ("F", "Female")] username = None # Removed username, using email instead email = models.EmailField(unique=True) user_type = models.CharField(default=1, choices=USER_TYPE, max_length=1) gender = models.CharField(max_length=1, … -
DJango and Docker: db shutting down and web service not accepting connections
I have a problem with Docker. I am trying to build a docker postgres DB and web service for a DJango app. Here is my config: Dockerfile: # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml: services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=whatsarounddb - POSTGRES_USER=dbadmin - POSTGRES_PASSWORD=dbadmin123 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=whatsarounddb - POSTGRES_USER=dbadmin - POSTGRES_PASSWORD=dbadmin123 depends_on: - db settings.py from Django: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] **code** # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'whatsarounddb', 'USER': 'dbadmin', 'PASSWORD': 'dbadmin321', 'HOST': 'localhost', 'PORT': 5432, } } When I use docker-compose up --build I get the following output: [+] Running 14/1 ✔ db 13 layers [⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿] 0B/0B Pulled 9.6s [+] Building 7.0s (14/14) FINISHED docker:default => [web internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [web internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 234B 0.0s => [web] resolve image config for docker.io/docker/dockerfile:1 1.5s => [web auth] docker/dockerfile:pull token for … -
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="{{ …