Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Code 1011 in django website Websockets connection
I have been working on a django chatting application (https://aniconnect.org) which uses daphne (django-channels) for the websocket functionality which allows users to chat with each other. Every time I open a chatroom, the websocket connection opens and closes instantly. Upon doing some debugging, I found out the error code was 1011. The following is consumers.py which handles websocket backend logic: from channels.generic.websocket import AsyncWebsocketConsumer import json from django.contrib.auth.models import User from .models import ChatRoom, Message, Profile #from channels.db import database_sync_to_async from asgiref.sync import sync_to_async @sync_to_async def save_message_to_database(chatroom_name, username, message): try: chatroom = ChatRoom.objects.get(name=chatroom_name) user = User.objects.get(username=username) user_profile = Profile.objects.get(user=user) new_message = Message.objects.create(chat_room=chatroom, sender=user_profile, content=message) print("Message saved to DB:", new_message) except ChatRoom.DoesNotExist: print(f"Chatroom with name '{chatroom_name}' does not exist.") except Profile.DoesNotExist: print(f"User profile with username '{username}' does not exist.") except Exception as e: print(f"Error occurred while saving the message: {e}") @sync_to_async def get_chatroom_by_name(name): try: return ChatRoom.objects.get(name=name) except ChatRoom.DoesNotExist: return None @sync_to_async def get_messages_for_chatroom(chatroom): return list(Message.objects.filter(chat_room=chatroom).order_by('timestamp')) class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() print(f"WebSocket connection opened for room: {self.room_name}") chatroom = await get_chatroom_by_name(self.room_name) if chatroom: print(f"Chatroom: {chatroom.name}") else: print(f"Chatroom '{self.room_name}' not found.") messages = await get_messages_for_chatroom(chatroom) for message in … -
How can I add a MultipleChoiceField field to ConfigForm (djconfig library)?
I have a form that I'm trying to add a MultipleChoiceField to. class BasicConfigForm(ConfigForm): site_name = forms.CharField(initial="Spirit", label=_("site name")) site_description = forms.CharField( initial="", label=_("site description"), max_length=75, required=False) site_wiki = forms.URLField( initial="", label=_("Wiki link"), required=False, widget=forms.URLInput(), help_text=( "Insert wiki link here")) bug_report_url = forms.URLField( initial="", label=_("Your bug report link"), required=False, widget=forms.URLInput(), help_text=( "Insert bug report link here (don't post anything if there is no link.)")) enabled_languages = forms.MultipleChoiceField( label='Enabled Languages', choices=base.LANGUAGES, widget=forms.CheckboxSelectMultiple, required=False, ) comments_per_page = forms.IntegerField( initial=20, label=_("comments per page"), min_value=1, max_value=100) topics_per_page = forms.IntegerField( initial=20, label=_("topics per page"), min_value=1, max_value=100) This field appears and displays fine, but when I try to save this form, everything except this field is saved. How can I make sure it is saved? my views: User = get_user_model() @administrator_required def config_basic(request): form = BasicConfigForm(data=post_data(request)) if is_post(request) and form.is_valid(): enabled_languages = form.cleaned_data['enabled_languages'] form.enabled_languages = enabled_languages form.save() messages.info(request, _("Settings updated!")) return safe_redirect(request, "next", request.get_full_path()) print() return render( request=request, template_name='spirit/admin/config_basic.html', context={'form': form}) I tried to override save() in BasicConfigForm, but I think I did it wrong. def save_enabled_languages(self): self.enabled_languages = self.cleaned_data['enabled_languages'] def save(self): self.save_enabled_languages() super(BasicConfigForm, self).save() -
I have react django app, and the problem while refresh page - opens API page
I have react django app, and the problem while refresh page - opens API page. All works good, but when page is refreshed suddenly opens Api page with many fields of django model, how to avoid that? Index.js file: ` import React from 'react'; import ReactDOM from 'react-dom/client'; import { createBrowserRouter, RouterProvider } from 'react-router-dom'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import App from './App'; import Lesson from './lessons/Lesson1'; import AllLessons from './pages/AllLessons'; import FormikLogin from './pages/FormikLogin'; import Home from './pages/Home'; import ErrorPage from './pages/Home' import LessonCreate from './pages/LessonCreate'; import LessonsByCategory from './pages/LessonsByCategory'; import LessonUpdate from './pages/LessonUpdate'; import RegisterFormik from './pages/RegisterFormik'; const router = createBrowserRouter([ { path: "/", element: <App />, errorElement: <ErrorPage />, children: [ {index: true, element: <Home />}, {path: "/api/users/login", element: <FormikLogin />}, {path: "/api/users/register", element: <RegisterFormik />}, {path: "/api/lesson/:pk", element: <Lesson />}, {path: "/api/create/lesson", element: <LessonCreate />}, {path: "/api/update/lesson/:pk", element: <LessonUpdate />}, {path: "/api/lessons/list", element: <AllLessons />}, // categories of lessons {path: "/api/lessons/:slug", element: <LessonsByCategory />}, // lessons by category ] } ]) const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <RouterProvider router={router} /> </React.StrictMode> ); ` urls.py file: ` from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from … -
The view account.views.user_login didn't return an HttpResponse object. It returned None instead
Cannot register or login account.views didn't return http response # accounts/views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, UserLoginForm def register(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') account = authenticate(username=username, email=email, password=password) login(request, account) return redirect('home') # Redirect to your home page else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form return render(request, 'accounts/register.html', context) def logout_view(request): logout(request) return redirect('home') def user_login(request): context = {} user = request.user if user.is_authenticated: return redirect("home") if request.POST: form = UserLoginForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: user_login(request, user) return redirect('home') else: form = UserLoginForm() context['login_form'] = form return render(request, 'accounts/login.html', context) I tried to register users but its telling me that my account.views is not returning an Http response but the users account will be updated in my django admin and if try to log in it still show the same error -
How to pass optional parameters to a view in Django?
I have a view that takes two optional keyword arguments: team and year_month def monthly_data_list(request, year_month:str=None, team=None): From the template, I want to call different combinations with either one of these 2 parameters, or both. Django docs gives this example of implementing this: path('monthly/list/', views.monthly_data_list, {'team':None, 'year_month'=None },name='monthly-data-list'), However, calling this URL from the template with one or both arguments gives me a NoReverseMatch error: hx-get="{% url 'drivers:monthly-data-list' team=None year_month=current_year_month %}" I found a workaround suggested here, which is to define paths for all combinations of parameters. This works with 2 parameters, but gets complicated on more. How do you correctly implement multiple optional parameters? -
social-auth-app-django. Associate a social account by custom field in UserModel
I have a custom user model: class Profile(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... telegram_id = models.BigIntegerField(verbose_name='телеграм ID', unique=True, blank=True, null=True) ... I have configured authorization via Telegram, Google, VK. After authorization via Telegram where do I get extra_data: {"id": ["123"], "first_name": ["123"], "last_name": ["123"], "username": ["123"], "photo_url": ["https://t.me/i/userpic/320/123"], "auth_date": ["123"], "hash": ["123"]} An instance Profile and social_auth_usersocialauth records is created. I want to do the following: If the user is new when logging in via Telegram it is checked whether a Profile exists, where Profile.telegram_id == extra_data["id"] If such a profile exists: Associate the record social_auth_usersocialauth with this Profile If not: Create a record Profile as standard I have the following social auth pipelines settings: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) I suppose I need to create my own pipeline where all the logic will take place, but I don't quite understand how to do it correctly so as not to break the logic of other backends. -
"How does quantum computing influence machine learning optimization, and are there practical implementations or case studies?" [closed]
The question delves into the intersection of quantum computing and machine learning optimization. It seeks information on the impact of quantum computing on the optimization of machine learning algorithms. Additionally, it asks for insights into practical implementations or case studies that showcase the application of quantum computing in enhancing machine learning optimization. This topic is at the forefront of technological advancements, exploring the potential of quantum computing in revolutionizing traditional machine learning approaches. -
Export enums with drf-yasg to Swagger: Works in responses serializers but not in query_serializer
I have a viewset with a method with this swagger_auto_schema decorator: @swagger_auto_schema( responses={200: MyResponseSerializer(many=True)}, query_serializer=MyQuerySerializer ) When I define serializers.ChoiceField(choices=...) in MyResponseSerializer, the enum for the choices are outputted to Swagger schema. When I use ChoiceField in MyQuerySerializer, this is not outputted. Is this by design? Is there a straightforward way of exporting choices enums for query_serializers, too? -
COSR error in react and drf website but no error in django website?
I have two websites one completely in django and another uses django rest framework and react, I am trying to redirect a to a particular URl and it works fine for the django application but I get error for the react application. Both uses this return HttpResponseRedirect(next_url). What is the reason for it? -
Where to place raw custom SQL queries in Django?
I have a simple views.py file from django.db import connection from rest_framework.views import APIView from rest_framework.response import Response class UsersView(APIView): def get(self, request): with connection.cursor() as cursor: cursor.execute("SELECT * FROM users") users_data = cursor.fetchall() return Response(users_data) def post(self, request): """ {"username": "Ivan", "bio": "Hi I am Ivan"} """ data = request.data username = data.get('username') bio = data.get('bio') with connection.cursor() as cursor: cursor.execute("INSERT INTO users (username, bio) VALUES (%s, %s)", [username, bio]) return Response("Ok") I am wondering how to organize my code when using raw SQL queries. I understand that the functionality demonstrated in my code can be easily achieved using the Django ORM; this is just an illustration. Should I concentrate all query logic within the serializers.py file, or would it be preferable to create a separate file for this purpose? Could you guide me or provide a resource that explains how to organize this? Here what is ChatGPT saying about this: *"When using raw SQL queries in Django, organizing the code is crucial for maintainability and clarity. It's recommended to separate concerns and maintain a clean structure. Consider these approaches: Services/Managers: Create separate modules like services.py or managers.py to contain functions that handle raw SQL queries. These modules encapsulate … -
Text input in list choice django form
I have two model in my project: Viaggio and Cliente. Viaggio has a Foreign Key of Cliente, so the basic structure is: class Viaggio(models.Model): nome = models.CharField(max_length=255, unique=True) cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE, null=True, blank=True, related_name='viaggi_cliente') class Cliente(models.Model): nome = models.CharField(max_length=255, unique=True) In the form of Viaggio i see the list of Cliente's values but i want that the user has the possibility to write for searching the value he wants. I have no idea how to achieve this. -
Logging a diff of updated model in Django Admin
Our team is trying to implement a logging solution for Django's Admin, where we would know not just which fields have been changed in latest CRUD operation on a specific model, but also the values that have changed - in short, along history we would also like a diff. We tried the post_save hook/override the save method, but that requires the overriding on every single model. EDIT: Forgot an important detail, we require this only for actions done via Django's Admin, not the rest of the code/API, ... -
Ngnix not connecting to Django/Gunicon container
I have a backend on DigitalOcean and i get a 502 when connecting to it The Ngnix error: 2023/12/01 10:05:43 [error] 31#31: *507 upstream timed out (110: Connection timed out) while connecting to upstream, client: 141.101.98.150, server: mydomaine.com, request: "GET / HTTP/1.1", upstream: "http://172.27.0.7:5001/", host: "mydomaine.com" Nginx config for dev container: server { listen 80; listen [::]:80; server_name mydomaine.com; return 301 https://$host$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name mydomaine.com; ssl_certificate /etc/nginx/ssl/fullchain.pem; ssl_certificate_key /etc/nginx/ssl/privkey.pem; access_log /var/log/nginx/dev_access.log; error_log /var/log/nginx/dev_error.log; location / { proxy_pass http://dev:5001; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } Docker compose file: version: "3.7" services: webserver: image: nginx:1.22.0 container_name: webserver restart: always ports: - 80:80 - 443:443 volumes: - ./logs/nginx/:/var/log/nginx/ - ./nginx/ssl/:/etc/nginx/ssl/:ro - ./nginx/configs/:/etc/nginx/sites-enabled/:ro - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro networks: - backend db_prod: image: postgres:15 container_name: db_prod restart: always ports: - "${POSTGRES_PROD_PORT}:5432" volumes: - db_prod:/var/lib/postgresql/data environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_DB: ${POSTGRES_DB} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_ENGINE: ${POSTGRES_ENGINE} # profiles: #TODO: fix Unsupported config option for services.{service_name}: 'profiles' # - prod networks: - backend db_dev: image: postgres:15 container_name: db_dev restart: always ports: - "${POSTGRES_DEV_PORT}:5433" volumes: - db:/var/lib/postgresql/data environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_DB: ${POSTGRES_DB} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_ENGINE: ${POSTGRES_ENGINE} # profiles: # - dev networks: - backend prod: build: ./src command: ["./start.sh"] … -
Second Record Occurs When the Form is Resubmitted by Pressing the Back Key from the Browser
When the user fills in the form and saves it, they are redirected to the next page. However, when the user presses the back button from the browser, the completed form is brought to the user from the browser cache. The user thinks that the form has been edited and when he/she makes the necessary edits and resubmits the form, a second record is created in the database. class UserFormView(FormView): def get(self, request, userformmodel_id = None): instance = get_object_or_404(models.UserFormModel, pk=userformmodel_id) if userformmodel_id else None form = forms.UserFormForm(instance=instance) if instance else forms.UserFormForm() context = { 'form' : form, } return render(request, 'formuser.html', context) def post(self, request, userformmodel_id=None): instance = get_object_or_404(models.UserFormModel, pk=userformmodel_id) if userformmodel _id else None form = forms.UserFormForm(request.POST, instance=instance) if instance else forms.UserFormForm(request.POST) if form.is_valid(): form.save(user_id=request.user.id) return redirect('other-page') context = { 'form' : form, I } return render(request, 'userform.html', context) I couldn't find any solution. The only solution is not to redirect the user to another page after submitting the form. -
which is better ajax or websocket for the client to receive 1 message from the server?
I have a Django site for processing pdf files. The user uploads the file and indicates what to do with it, after which the file is sent to the server and transferred to the celery task. Meanwhile, I redirect the user to the page with the loader and he waits for the result to arrive (a link to download the result should appear). And I had a question - how can I send a message (a link to download the result) to the client from the server when the task is completed - establish a websocket connection in order to send or use ajax constantly asking the server if there is no result yet? I have the following selection criteria: an instant message from the server is not mandatory for me (there may be a delay of 2-3 seconds); the duration of file processing will take a maximum of 10-15 seconds; if I use ajax, I will send requests to the server every 2 seconds; I need to choose an option that will be less expensive in terms of resources. I've read a lot about these technologies, but I couldn't figure out what would be better. I will be grateful … -
I am building a website about group budgeting something in Django. Remark "pending, "not pending", "paid" not working well
If i am using an admin account, i want my remark to be "Paid" if all members submitted a proof file and otherwise, "Pending". And if i am using a member account, i want my remark to be "Paid" if i submitted a proof file and otherwise, "Not Paid". Now, the problem is even though all members submitted proof, the remark is still "Pending" same with inside the members account, the remark is "Not Paid" although it has submitted proof. Can anyone help me fix this please. I am in rush. Models.py class bills(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) amount = models.IntegerField() remarks_admin = models.CharField(max_length=255, default="") remarks_member = models.CharField(max_length=255, default="") title = models.CharField(max_length=30) due = models.DateTimeField(null=True) assigned = models.DateField(auto_now=True) slug = models.SlugField(null=False, blank=False, default="") class Submission(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bills = models.ForeignKey(bills, on_delete=models.CASCADE) proof = models.FileField(null=True) bills.html ```{% extends "base/base.html" %} {% block content %} <div class="container"> <div class="row justify-content-center align-items-center" style="height: 100vh;"> <div class="col-md-6"> <h1 class="text-center">{{ room.title }}</h1> <div class="form-group text-center"> <p>Room Code: <br><b>{{ room.join_code }}</b></p> </div> <a href="{% url 'post-bills' room_id=room.join_code %}"> <button type="button" class="btn btn-primary btn-lg">Add Bills</button> </a> <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Title</th> <th scope="col">Amount</th> <th scope="col">Due Date</th> <th scope="col">Remarks</th> </tr> </thead> <tbody> … -
got problem with the websocket with python/django
Im trying to make notification for my project but Im having problem with my DB and api first Im using postgreSQL but my models.py does not upload on db second so I made db on admin page and it actually uploaded on my db so I checked on my developer's tool, they did actually brought API but empty so I need help on those 2 issues can't upload notification models on pgadmin when I leave a comment on my project when I passively upload data at db on admin it worked but still API is empty here are some of my project works Thank you views.py class NotificationCreate (APIView): # 로그인 한 유저만 가능 permission_classes = [IsTokenValid] # IsTokenValid 권한을 적용 def post(self, request): print("Notification_post") content = request.data.get('content') notifications = Notifications(content=content) notifications.save() serializer = NotificationSerializer(notifications) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self,request): print("Notification_get") notifications = Notifications.objects.all() serializer = NotificationSerializer(notifications, many=True) return Response(serializer.data, status=status.HTTP_200_OK) class CommentCreateAPIView(APIView): permission_classes = [IsTokenValid] def post(self, request, study_id, story_id): print("Comment_post") # 사용자로부터 댓글 내용을 받아옵니다. content = request.data.get('content') article_type = request.data.get('article_type') # 'study' 또는 'story' article_id = request.data.get('article_id') # 게시물의 ID user = get_user_from_token(request) # 실제로 댓글을 생성하고 데이터베이스에 저장하는 코드 (예시) # Comment 모델이 있다고 가정하고 사용자 … -
Add appointment funtionality for my django app using Google calendar API
i am working on django app where patient and doctor interact , i want to add appointment funtionality for patient. Details: 1.The patient user should be able to see a list of all the doctors in the system 2.Each list item should have: Profile picture Name A button “Book Appointment” 3.Upon clicking that button the patient user should see a form with following: Required speciality Date of Appointment Start Time of Appointment A confirm button 4.Each appointment will be of 45 mins 5.When user clicks on confirm a calendar event has to be created for the doctor user 6.On confirmation the patient should see a screen with the appointment details: Doctors Name Appointment date Appointment start time Appointment end time(to be calculated by the application) here my code link :https://github.com/geetanshpardhi1/intern_task_1 Please help me to code. -
Accss ManyToMany through model attribute for spcific row in drf serilizaer
I'm using Django 4.2 with Django-rest-framework and I need some help with returning a serialized object. I have 2 models that have many to many relationship using a through model to hold a bit more logic I want to return a serialized object that includes an extra attribute from the through model. How can I do that? My models: class Chart(models.Model): name = models.CharField(max_length=255, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: ordering = ['id'] def __str__(self): return self.name class MonitoredFlow(models.Model): name = models.CharField(max_length=255, unique=True) charts = models.ManyToManyField(Chart, through="ChartFlows", related_name="monitored_flows", through_fields=("monitored_flow", "chart") ) class Meta: ordering = ['id'] def __str__(self): return self.name class ChartFlows(models.Model): chart = models.ForeignKey(Chart, on_delete=models.CASCADE) monitored_flow = models.ForeignKey(MonitoredFlow, on_delete=models.CASCADE) is_visible = models.BooleanField(default=True) class Meta: ordering = ['id'] def __str__(self): return f"{self.chart.name}: {self.monitored_flow.name}" When retrieving a Chart object, I would like to know for the monitored flow if he is visible (or not) on the specific chart. I would like to get from my view or serializer an object that looks something like this: { "id": 1, "name: "some chart name", "monitored_flows": [ "id": 1, "name": "some flow name", "is_visible": true ] } My challenge is how to add the is_visible attribute from the through model. Thanks for the … -
Django user authentication with phone and Email
I want to customize my Django user authentication system so users can sign up/in with both phone number and email (OTP and password). What should I do? How can I customize my user model? Should I use AbstractUser or AbstractBaseUser or something else? -
TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile uploading file by Django [closed]
I am getting this error to upload my file to google drive I am uploading excel file, but it works fine if I upload .py or .txt gauth = authenticate() drive = GoogleDrive(gauth) gfile = drive.CreateFile({'parents': [{'id': config('ID')}]}) # gfile['title'] = file_name gfile.SetContentFile(uploaded_file) gfile.Upload() -
Django file uploading function can run in localhost but can't run in EC2 instance of AWS
So I'm trying to create a chatbot webapp that can do data analysis from an excel, csv, google spreadsheet, and all sorts. It's good when I ran it in the local anaconda environment, and now I want to set it up in the AWS EC2. But then things happen, you see when I get it run in the locals it doesn't give error on the inspect and then comes this new 2 error: POST https:/demo.myapp.company/upload/ 500 (Internal Server Error) Error uploading file: Error: Network response was not ok Internal Server Error at (index):646:16 But in my local anaconda environment it doesn't yield that, as a matter fact it always successfully uploaded files with no fail (around 50 times as per now without any error). I asked openai's chatgpt and says this error falls on the server side and has nothing to do with the code so then I tried using all 12 suggestions and nothing worked, anyone familiar with this kind of error? The app pipeline will look like this: User clicked the upload button and select the excel file, here's how the file is handled in django: On the views.py: import requests, boto3, pandas, etc. def file_upload(request): act = … -
How to expire / invalidate simple jwt token in Django rest framework
How can I invalidate the user token when the user status changes (banned/inactive) by the admin? I am new to Django. -
Django websocket code is skipped when running server via nginx and asgi
In our code, AsyncJsonWebsocketConsumer.send_json() works fine when we are running the server via Django runserver but gets skipped when it is ran via nginx and asgi. This is the calling code and it is within an api view: async_to_sync(channel_layer.group_send)( 'office_id_{}'.format(patient.office.pk), { 'type': 'message_received', 'patient_id': patient.id, } ) message_received looks like this: async def message_received(self, event): await self.send_json(event) What do we have to do to get this to work under nginx and asgi? Thanks, -
Prevent Django management commands from stripping out quotes from arguments
I have a Django management command mycommand.py with an argument that accepts a JSON-formatted string, like: from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('json_str') def handle(self, json_str, **options): print('json_str:', json_str) However, if I run this from Bash: python manage.py mycommand '[123, "abc"]'` the output I see is: [123, abc] which is invalid JSON since the quotes have been stripped out. Is this being done by Bash or by Django, and how do I stop it? Attempting to use \ to escape the quotes in Bash has no effect.