Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make djangoq tests use the same test database as pytest
I was beginning to write some tests that involve async tasks, and I realised these tests (using pytest-django) were failing because the async job isnt pointed at the right database. How does one point django-q /qcluster to look at the test database that pytest uses. I am mostly using the default settings from Django. DATABASE related settings.py looks like this 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'TEST': { 'NAME': BASE_DIR / 'testdb.sqlite3'} I am running this to check what is the db being connected to. from django.db import connection db_name = connection.settings_dict['NAME'] When the function is being run in non async mode - it rightly points to the testdb.sqlite3. When run using async mode, it points to the db.sqlite3. How do i make the async task to refer to the testdb. Any pointers would be very helpful. -
Django JsonResponse customize its header
I want to change response header of > from django.http import JsonResponse function for example change Date header how? -
Django fixing migrations order for unit testing
I'm working on a codebase which has a lot of migrations. We also have SQL views which are defined in the migrations and later updated in the migrations (whenever changes to the SQL views were required). We have a challenge where when running unit tests the migrations are not applied in the same appear as they currently appear in the django_migrations table. This causes unit tests to fail. My thought is, I could probably write a script to the dependencies of all the migrations files to follow the same order of django_migrations thus ensuring that migrations are run in the correct order. Then I can look into squashing migrations. But this is a lengthy process and I'm not sure if this will actually work. Has anyone come across this issue before? If so, how did you overcome it? -
Different websocket endpoints with Apache2 vs "manage.py runserver". Django Channels
I have different endpoints when i run Django in apache compare to when I run it in the terminal. Can it be some configuration in apache? I belive it can be this ? Apache 2 conf ProxyPass "/ws/" "ws://127.0.0.1:8000/" What does this mean; "/ws/"? Apache to work: ws_urlpatterns = [path('some_url/', Andring.as_asgi()), ] Run in terminal: ws_urlpatterns = [path('ws/some_url/', Andring.as_asgi()), ] In JS: const socket = new WebSocket("ws://" + window.location.host + "/ws/some_url/"); -
How can I use html tags on Django template?
As seen in the image, I am working on a django template, but when I try to write HTML tags, it does not offer any suggestions. When I replace Django Template with HTML, it does not detect commands written for django. In the videos I watched, they can call HTML tags without any problems, using the Django template. Do I need to add any extension or something? -
django-plotly-dash Cannot find Dashapp in the query
I've been trying to implement a dashapp into my django project, and I'm doing so by following the demonstration of the official documentation of django-plotly-dash. Weirdly enough my Dashapp does not get registered, the queryset in def get_object_or_404(klass, *args, **kwargs): which is in django shortcuts.py is returned empty, whereas in the working example it is a list of Dashapp objects registered. Any help is much appreciated. -
Create superuser for cvat
I am trying to install cvat, so I am following the Installation guide The first step run smoothly, however when I try to create a superuser with the command docker exec -it cvat_server bash -ic 'python3 ~/manage.py createsuperuser' After a few minutes, I get the following error: Traceback (most recent call last): File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/opt/venv/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection timed out Is the server running on host "cvat_db" (172.18.0.3) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/django/manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/opt/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/opt/venv/lib/python3.8/site-packages/django/core/management/base.py", line 397, in execute self.check_migrations() File "/opt/venv/lib/python3.8/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) … -
Is it possibile to have two backends in single app, and should I do it?
I am building a web app using PHP Symfony as the backend. I need to connect my backend with some controllers using TCP protocol(websockets). I need to start the socket connection and keep it alive for a period of time and wait for any messages sent from a socket. I tried so many ways, including using Ratchet library for Symfony, and can't get it to work correctly. I have done the same thing in python with ease and tried running that script from PHP, but it's also kind pain to do. So now I wonder, what if I set up another backend on that server, with python Django to handle socket connections? They would be using the same database and communicating only with the front end, not in between. -
Problem with Django StreamingHttpResponse
I'm having a problem with Django response class StreamingHttpResponse. When I return a generator as response using StreamingHttpResponse and make a request I excepted to retrieve each data block one by one, instead of that i retrieve the full data at once when the generator loop has finished. My Django View: def gen_message(msg): return '\ndata: {}\n\n'.format(msg) def iterator(): for i in range(100): yield gen_message('iteration ' + str(i)) print(i) time.sleep(0.1) class test_stream(APIView): def post(self, request): stream = iterator() response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream') response['Cache-Control'] = 'no-cache' return response And I make the request like that: r = requests.post('https://******/test_stream/', stream=True) for line in r.iter_lines(): if line: decoded_line = line.decode('utf-8') print(decoded_line) When I see the output of the Django server I can see the print every 0.1 seconds. But the response in the second code only shows when the for loop is finished. Am I misunderstanding the StreamingHttpResponse class or the request class or is there another problem? Thanks:) -
SAMLRequest and Signature parameters in SSO
I am using django-saml-sp library, I have one working idp and I try to implement SSO log in to my Django project. For doing it, I need to generate SAMLRequest and Signature parameters in the query string to redirecting SSO Log on page. I couldn't find a way to do that. -
How can I get the list of user from group after filtering in Django-template-language
In the below image How can I get filtered users Right now I am rendering the users with : <div class="row-sm-3"> <div class="container d-flex"> <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <select name="select" class="form-control" id="mySelect" onchange="myFunction()"> {% for group in groups %} <option selected="selected" >{{group.name}}</option> {% endfor %} </select> <input class="btn btn-sm btn-primary" type="submit"> </form> </div> </div> -
Django Admin custom field in ModelForm is displayed as blank after being set in get_readonly_fields
I am using python 3.10 and Django 4.1 The model I'm making an admin panel for has a JSONField that will hold values from dynamically created form fields in the Admin panel. The issue is that I should be able to also dynamically set them to readonly from the AdminModel using the get_readonly_fields method. To do that I made a custom ModelForm which adds new fields inside the _init_ method. class CustomForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomForm, self).__init__(*args, **kwargs) for name in dynamic_fields_names(): self.fields[name] = forms.ChoiceField(choices=dynamic_fields_values(name)) def clean(self): cleaned_data = super(ExecutionAdminForm, self).clean() for name in dynamic_fields_names(): self.instance.description_fields[name] = cleaned_data.pop(name) class Meta: model = Execution fields = "__all__" @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): form = CustomForm def get_form(self, request, obj=None, **kwargs): kwargs["fields"] = admin.utils.flatten_fieldsets(self.fieldsets) return super(MyModelAdmin, self).get_form(request, obj, **kwargs) def get_fieldsets(self, request, obj): return ( (None, {"fields": ("user", "status")}), ("Description", {"fields": dynamic_fields_names()}) ) def get_readonly_fields(self, request, obj): if can_change_dynamic_fields: return [] return dynamic_fields_names() When I set them to readonly using get_readonly_fields they are rendered as empty inside the browser Not set as readonly Set as readonly -
How to iterate over 2 variables in Django template
I have an app for some quiz with questions and choices. So I'm trying to render all this stuff to Django templates. In my views.py it looks like this def choice(request): question_list = get_list_or_404(Question) page = get_object_or_404(Page, name='about') letters = ["A", "B", "C", "D", "E"] return render(request, 'qview/choice.html', { 'question_list': question_list, 'page': page, 'letters': letters, } ) I have a list of questions and list with letters. All of that I'm sending as context to my template. {% if question_list %} <ul> {% for question in question_list %} <li><a href="#">{{question.question}}</a></li> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.text }}</li> {% endfor %} </ul> {% endfor %} </ul> {% else %} <p>No questions available</p> {% endif %} So here I'm going through all of questions and all of choices connected to this question. But I can't get how I can also go through letters list? I was thinking about zip it all. But in view I have only questions not choices, so I can't zip to it. So what else is possible here? -
Problem with Bind mount on Azure Web App Service for Containers with docker-compose
I have a problem with starting my_app on Azure Web App Service for containers. I followed few tutorials and checked this amswer but I still get the following error: ERROR - Exception in multi-container config parsing: YamlException: (Line: 22, Col: 9, Idx: 498) - (Line: 22, Col: 37, Idx: 526): Bind mount must start with ${WEBAPP_STORAGE_HOME}. My docker-compose file looks like this: version: '3' services: db: container_name: my_app_django_db image: postgres:14.5-alpine volumes: - postgres_data:/var/lib/postgresql/data/ networks: - my_app_network env_file: - ./.env.prod app: container_name: my_app_django_app build: context: ./backend dockerfile: Dockerfile.prod restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/:/usr/src/backend/ networks: - my_app_network ports: - 8000:8000 env_file: - ./.env.prod depends_on: - db react: container_name: my_app_react_app build: context: ./frontend dockerfile: Dockerfile.prod restart: always command: npm start volumes: - ./frontend/:/usr/src/frontend/ networks: - my_app_network ports: - 3000:3000 env_file: - ./.env.prod depends_on: - app redis: container_name: my_app_redis image: redis:7-alpine ports: - 6379:6379 networks: - my_app_network celery_worker: container_name: my_app_celery_worker restart: always build: context: ./backend command: celery -A my_app_settings worker --loglevel=info --logfile=logs/celery.log volumes: - ./backend:/usr/src/backend networks: - my_app_network env_file: - ./.env.prod depends_on: - db - redis - app celery-beat: container_name: my_app_celery_beat build: ./backend command: celery -A my_app_settings beat -l info volumes: - ./backend:/usr/src/backend networks: - my_app_network env_file: - ./.env.prod … -
Django with mqttasgi, how to update the db with contents of received messages
I have a Django project that reads messages from mqtt using mqttasgi I can see the messages in the mqttasgi output mqttasgi --host localhost --port 1883 myapp.asgi:application 2023-01-10 18:08:55.380206 -- Received a message at topic: test/device/online With payload: b'true' And QOS: 1 what I want to do is search for device in the message and then update the model just like I do with the web interaction I tried importing the model into the consumer import json from datetime import datetime from mqttasgi.consumers import MqttConsumer import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'boat.settings') django.setup() from .models import Device class MyMqttConsumer(MqttConsumer): async def connect(self): await self.subscribe('sirjames/#', 2) async def receive(self, mqtt_message): print(f"{datetime.now()} -- Received a message at topic: { mqtt_message['topic'] }") print(f"With payload: { mqtt_message['payload'] }") print(f"And QOS: { mqtt_message['qos']}") (site, devicename, topic) = f"{mqtt_message['topic']}".split('/',2) device = Device.objects.get(name=devicename) if topic == 'online': if mqtt_message['payload'].decode('UTF-8') == 'false': device.online = False device.save() else: device.online = True device.save() pass async def disconnect(self): await self.unsubscribe('sirjames/#') but as soon as I do that then mqttasgi complains about it django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How do I modify the code so that the db update works? -
I'm a newbie to python/Django and getting a value error and no http response error. Please can anyone tell me what's wrong?
ValueError at /update_department/14 The view management.views.update_department didn't return an HttpResponse object. It returned None instead. Request information USER admin GET No GET data POST Variable Value csrfmiddlewaretoken 'XLqZBPhMKImvlfgWsNLeN1Ei8nz5u1HJ15IvAQV4JNwVMeG31rhDOD1q9PJuwXmz' department_code '15' department_name_e 'Finance' department_name_l 'Finance' parent_code '' submit '' These are the details.I don't know why is there error here while all the posted data is right.also the form is not updating. Models: class Departments(models.Model): department_code = models.CharField(db_column='Department_Code', primary_key= True, max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. department_name_e = models.CharField(db_column='Department_Name_E', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. department_name_l = models.CharField(db_column='Department_Name_L', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. parent_code = models.CharField(db_column='Parent_Code', max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. is_active = models.BooleanField(db_column='Is_Active') # Field name made lowercase. created_by = models.IntegerField(db_column='Created_By') # Field name made lowercase. created_date = models.DateTimeField(db_column='Created_date') # Field name made lowercase. modified_by = models.IntegerField(db_column='Modified_By') # Field name made lowercase. modified_date = models.DateTimeField(db_column='Modified_date') # Field name made lowercase. class Meta: db_table = 'Departments' unique_together = (('department_code'),) def __str__(self): return str("self.department_name_e") or '' View: @login_required def update_department(request, department_code): dep_up = Departments.objects.get(department_code=department_code) if request.method == "POST": form = DepartmentsForm(request.POST, instance = dep_up) if form.is_valid(): department_code = form.cleaned_data['department_code'] department_name_e = form.cleaned_data['department_name_e'] department_name_l = form.cleaned_data['department_name_l'] parent_code = form.cleaned_data['parent_code'] obj = form.save(commit = False) obj.is_active = True … -
How can I get deleted object? I want to upload the object that has been deleted before but since some fields have unique=True, I get integrity error
this is my model this is my delete function I tried getting the firmware whose field of is_delete=True -
Problem with the JWT token to interact with google cloud
The following code is used to create a JWT for a google cloud service called fleetengine this code was working and suddenly it creates a wrong token the sad thing is that it is working on my friend's device with the same code without any changes. def generate_token(role='server', **kwargs): iat = time.time() exp = iat + 3600 if role == 'consumer': iss = CONSUMER_SERVICE_ACCOUNT_EMAIL sub = CONSUMER_SERVICE_ACCOUNT_EMAIL authorization = { "trackingid": kwargs.get('tracking_id') } elif role == 'driver': iss = DRIVER_SERVICE_ACCOUNT_EMAIL sub = DRIVER_SERVICE_ACCOUNT_EMAIL authorization = { "deliveryvehicleid": kwargs.get('vehicle_id') } else: iss = SERVER_SERVICE_ACCOUNT_EMAIL sub = SERVER_SERVICE_ACCOUNT_EMAIL authorization = { "taskids": ["*"], "deliveryvehicleid": "*", "tripid": "*", "vehicleid": "*" } payload = {'iss': iss, 'sub': sub, 'aud': 'https://fleetengine.googleapis.com/', 'iat': iat, 'exp': exp, "authorization": authorization, } private_key = SERVER_GOOGLE_FLEET_ENGINE_SECRET_KEY.replace('\\n', '\n') additional_headers = {'kid': SERVER_GOOGLE_FLEET_KEY_ID, 'alg': 'RS256', 'typ': 'JWT'} signed_jwt = jwt.encode(payload, private_key, headers=additional_headers) return str(signed_jwt), iat, exp -
Execute function from an already rendered page django - Execute multiple function from an url
Quick question: What’s the best way / practise to execute a function (called from a form with POST) in a page which was render and generated by another function ? Context : Imagine page/id_48/ , all information and even the page is generated and render by a function My question is oriented with the path, as the path of the page is already use in urls.py to to execute the function which render the page Thank’s ! -
How to implement observer pattern the way django signals implements it
there's a design issue i have with a problem i'm currently working that will require a certain observable to emit values whenever it reaches a computation milestone,so i need values emitted intermediately,i discovered django implements something similar with signals which is just an implementation of the observer pattern but i really wanted to implement it the way django signals is implemented because observers subscribing to an observable( e.g after saving a model to the db i.e post_save signal) is very much decoupled in the sense that the observing function only needs to be annotated with the @receiver decorator. So i took a look at django's source code and tried creating a simple version of the signal mechanism i created a signals class in one module with the decorator : class Signal: def __init__(self): self.observers=[] def connect(self,receiver): self.observers.append(receiver.__name__) def send(self,sender,**named): return [ (receiver,mem_dec(signal=self,sender=sender,**named)) for receiver in self.observers ] class Child(Signal): def __init__(self): super().__init__() def mem_dec(signal,**kwargs): def wrapper(func): signal.connect(func, **kwargs) return func return wrapper if __name__ == "__main__": send_signal=Child() send_signal.send(sender="class_child",a="henry") and i placed the decorated function in another module to serve as the observer: from .signals import mem_dec from .signals import Child @mem_dec(Child,sender=Child) def hello(a,**kwargs): print(f'hey {a}') i noticed in my implementation … -
How can I access the values of this object in javascript?
[] I'm building a django webapp. When I access my backend for user information, I get an object in the following format according to console.log: { "email": "foo", "id": 1, "name": "bar" } However when I try to access something like(https://i.stack.imgur.com/Gu5EX.png) "userInfo.name", I get the error : Cannot read properties of undefined (reading 'name') From what I've read this is because this is not actually a JSON object and console.log is 'lying' to me. I've tried multiple other methods and they all throw up similar errors, including: userInfo[name] userInfo['name'] userInfo[0] userInfo[1] Object.keys(userInfo) I've also tried JSON.stringify -ing and JSON.parse -ing the object, as well as doing both. JSON.stringify returns a string that LOOKS like JSON to me: {"email":"foo@gmail.com","id":1,"name":"bar"}, but JSON.parse still will not parse it, and I still cannot access any of the values. -
how to create a GET request using gcloud function python
This is my gcloud function import firebase_admin from firebase_admin import credentials from firebase_admin import firestore import functions_framework if (not len(firebase_admin._apps)): firebase_admin.initialize_app() # Register an HTTP function with the Functions Framework @functions_framework.http def callback(request): db = firestore.client() request_json = request.get_json(silent=True) if not(request_json): return {'response':"Server error: no payload","code":101} ### Define variables sessionId = request_json['sessionId'] serviceCode = request_json['serviceCode'] text = request_json['text'] return text and when i evoke it with postman i get the error That’s an error. Your client has issued a malformed or illegal request. That’s all we know. what might be the problem -
Pylint warn the usage of print statement
I am using pylint_django for my django project. And I want to disable print statement usage or warn about it at least. Because I am using custom logger class. But there is no any warn about usage of print. extension-pkg-whitelist= ignore=CVS ignore-patterns= jobs=1 limit-inference-results=100 load-plugins= persistent=yes suggestion-mode=yes unsafe-load-any-extension=no [MESSAGES CONTROL] confidence= disable=missing-docstring, invalid-name, astroid-error, protected-access, broad-except enable=c-extension-no-member, print-statement [REPORTS] evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) output-format=text reports=no score=yes [REFACTORING] max-nested-blocks=5 never-returning-functions=sys.exit [LOGGING] logging-format-style=old logging-modules=logging .... How can i solve this issue? VsCode settings.json { "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.linting.flake8Enabled": false, "python.linting.prospectorEnabled": false, "python.linting.pylintArgs": [ "--load-plugins=pylint_django", "--rcfile=.pylintrc", "--enable=print-statement" ] } -
How to change subscription from PlanA to PlanB using Stripe with Python/Django
I can create a Stripe subscription for a customer using the following code : subscription = stripe.Subscription.create( customer=stripe_customer_id, items=[ { "plan": stripe_plan_A }, ] ) I want to change the upgrade the subscription to stripe_plan_B but while keeping rest of the configuration same. I have experimented with the following code to change the plan from stripe_plan_A to stripe_plan_B; however this following command results in having two subscriptions at the same time, rather than a single subscription. stripe.Subscription.modify( subscription.id, items=[ { "plan": selected_membership.stripe_plan_B }, ] ) Is there any suggestion for this, so I can fluently change between the plans ? -
Django - How to navigate between multiple apps
I'm a beginner in Django and don't understand how the templates "dirs" in setup.py works In my project directory, I have 2 apps. I want to reach them via a navigation bar. In the Navigation bar, I have "Home" "Manipulation" "Visualization" I can reach Home and Manipulation page, but when I try to reach the Visualization page, the browser shows me the Manipulation page again. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'manipulation/templates/manipulation'), os.path.join(BASE_DIR, 'visualization/templates/visualization'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Somebody can help me please? Thank you very much In Dirs : [], when I swap the order and put the "Visualization" path before the "Manipulation" path, I get the Visualization page instead of the Manipulation page