Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Postgres Docker First Migration Failing
I am having some difficulty in setting my app up to be dockerised. It runs locally without a problem using sqlite. I can delete the sqlite db and run the migrations from scratch and then migrate each of the apps after that. I can make all the migration files in advance and then delete the sqlite db and run it again from the command line and run manage.py migrate and all tables are created correctly. All good. However! When I try and dockerise it it all seems to fall apart. Here is my docker-compose file which creates the postgres container and the django container correctly and I can shell into the django container and connect to the database from the command line using psql and the configured parameters. version: '3.8' services: web: build: context: . ports: - 80:8000 depends_on: db: condition: service_healthy environment: - DATABASE_ENGINE=django.db.backends.postgresql - DATABASE_NAME=project - DATABASE_USER=project - DATABASE_PASSWORD=postgres - DATABASE_HOST=db - DATABASE_PORT=5432 - PORT=8000 - DEBUG=False #command: python3 manage.py runserver 0.0.0.0:8000 command: ping google.com networks: - project-network db: image: postgres:15.2-alpine environment: - POSTGRES_USER=project - POSTGRES_PASSWORD=postgres ports: - 5432:5432 networks: - project-network healthcheck: test: "pg_isready --username=project && psql --username=project --list" timeout: 10s retries: 20 networks: project-network: name: project_network … -
500 (Internal Server Error) Django and Vue.js
When I try to submit a form from vue.js, this error shows up, everything else works correctly, all I need is to send the form to my django project / views to treat the data the thing that doesnt happens due to this error here is my submit function: handleSubmit(){ if(this.nom == '') this.nameError = "Vous devez saisir votre nom" this.pwdLengthError = this.password.length >= 5 ? '' : 'Le mot de passe doit contenir 5 caracteres au minimum !' console.log(this.pwdLengthError) if(this.password != this.passwordConfirm) this.pwdConfirmError = "Vous n'avez pas saisi le meme mot de passe" else this.pwdConfirmError = '' console.log(this.pwdConfirmError) const consultant = { nom: this.nom, prenom: this.prenom, username: this.username, password: this.password, email: this.email, telephone: this.telephone, adresse: this.adresse, } axios .post('/createConsultant/', consultant) .then( res => { console.log(res) } ) .catch( err => { console.log(err) } ) }` and the createConsultant in views.py: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import Consultant @csrf_exempt def createConsultant(request): if request.method == 'POST': nom = request.POST.get('nom') prenom = request.POST.get('prenom') username = request.POST.get('username') email = request.POST.get('email') telephone = request.POST.get('telephone') adresse = request.POST.get('adresse') password = request.POST.get('password') print(nom, prenom) consultant = Consultant(nom=nom,prenom=prenom,username=username,email=email,telephone=telephone,adresse=adresse,password=password) consultant.save() return HttpResponse('Consultant created successfully') I already have the url … -
It says that the sender and **kwargs arguments are not working? I am trying to use post save and post delete signals
Here is the image of code also this is not accessable -
Saving file asynchronously on Django
I have a Django storage (boto3) that saves my files at some point during request/response cycle. I need to speed up the cycle, so I decided to save the file in an async manner. my code (storage) from asgiref.sync import sync_to_async from storages.utils import clean_name import asyncio class FileStorage(S3Boto3Storage): bucket_name = '####' async def _save(self, name, content): # save it in async mode await asyncio.create_task(sync_to_async(super()._save)(name, content)) # return super()._save(name, content) return clean_name(name) But I am getting this error now: File "...lib/python3.9/site-packages/django/core/files/storage.py", line 58, in save validate_file_name(name, allow_relative_path=True) File "....lib/python3.9/site-packages/django/core/files/utils.py", line 9, in validate_file_name if os.path.basename(name) in {"", ".", ".."}: File "...lib/python3.9/posixpath.py", line 142, in basename p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not coroutine -
I am facing issue in django [closed]
showing error :ImportError: cannot import name 'roll_dice' from 'utils' ` i am trying to solve - -pip install 'utils' make utils.py new dictionary But issue is not solved -
How to fix empty csv file after downloading from HTML website with Python in Django?
Looking forward to fix empthy csv file issue inside my Django project. I'm testing Youtube API where I'm fetching suggestion to my youtube.html website. I created Download as CSV button and after cliking it I'm downloading empty csv file. My source code in Github here: https://github.com/Vy7au7as/API.git Any suggestions how to download all results to csv WITHOUT saving inside database? I'm trying to download all results into csv file, but files it's empty... -
How to remove a tag when scraping
<p class="hidden-xs text-muted"> <b>GMC:</b> 123456 </p> I simply need the GMC number from here which will appear as GMC : 123456 when I scrape it. How to remove the "b" tag from there? I am using python 3.10.5 and BeautifulSoup. from bs4 import BeautifulSoup import requests def proxy_request(url): response = requests.get(url) return BeautifulSoup(response.text, 'lxml') url = "www.domain.com" # not mentioning the domain here soup = proxy_request(url) media_body = soup.find("div", {"class":"media-body"}) gmc_number = media_body.p.text.strip() output is like this, GMC: 123456 expected output, 123456 -
how can i provide a confirmation form in the properties_list view before deleting the property
the code below deletes the property directly when the user clicks the delete btn, how can i edit the code to provide a confirmation form i.e modal where the user can choose to either delete or not. views.py def property_list(request): properties = Property.objects.all() context = { 'properties': properties, 'delete_template':'real_estate/property/delete.html', } return render(request, 'real_estate/property/list.html', context) def delete_property(request, id): property = get_object_or_404(Property, id=id) if request.method == 'POST': property.delete() messages.success(request, f"you have successfully deleted {property.title}") return redirect('real_estate:property_list') context = { 'property': property, 'confirm_template':'real_estate/property/delete.html', 'confirm_url': reverse('real_estate:delete_property', args=[property.id]) } return render(request, context['confirm_template'], context) real_estate/property/list.html' {% extends "real_estate/base.html" %} {% block title %} Property List {% endblock %} {% block content %} {% if properties %} <h1>properties list</h1> <a class="btn" href="{% url 'real_estate:add_property' %}" >add property</a> <ul> {% for property in properties %} <li> <a href="{% url 'real_estate:property_details' property.id %}"> {{ property.title }} </a> <a class="btn btn-primary" href="{% url 'real_estate:property_details' property.id %}">View</a> <a class="btn btn-warning" href="{% url 'real_estate:edit_property' property.id %}">Edit</a> {% if request.GET.delete and request.GET.delete == property.id %} {% include confirm_template with property=property %} {% else %} <form action="{% url 'real_estate:delete_property' property.id %}" method="post"> {% csrf_token %} <button type="submit" name="delete">Delete</button> </form> {% endif %} </li> {% endfor %} </ul> {% else %} <h1>no properties added</h1> <a … -
getting static file for django with nginx
im trying to get static files in django, when using an nginx reverse proxy, dockerized in an ec2 container i have a django project and when it is dockerized with nginx as a proxy server i can not find my static files my default-ssl.conf.tpl for my nginx server has location /static{ alias /vol/static; } and my dockerfile for nginx says to creates a volume for vol/static VOLUME /vol/static VOLUME /vol/www so i manually put my files in there with docker cp and check with exec to make sure they're there my files are now in vol/static on my proxy container. so i think they should be handled properly now i still get GET https://tgmjack.com/static/health_hud.png 404 (Not Found) :( what might i have done wrong? what other info would be useful? my full code is here incase that might reveal what ive done wrong https://github.com/tgmjack/god_help_me extra info im deploying on an ec2 container i can connect to my custom domain with https and everything seems to be fine except the files cant be found -
HTMX load partials based on URL
Question: How do I have HTMX load a partial based on a URL that the user manually navigated to? I am using HTMX to load HTML partials. All partials come from their own endpoint. So in this example, it is coming from /h/library/1 where as the page is simply /library/1 My URL patterns are as such: urlpatterns = [ path("", login_required(views.logged_in_home), path("library/<id>", login_required(views.logged_in_home)), path("h/library/<id>", login_required(views.show_library)), # returns partial ] The button to load the library looks like this: <a hx-get="/h/library/1" hx-push-url="/library/1" hx-target="#page-content" hx-swap="innerHTML" > Load Library 1 </a> <div id="page-content"></div> When I click the link, the partial gets loaded correctly into the div and the url updates with /library/1. However, when I manually navigate to /library/1, I get the homepage, but the partial doesn't load. What the heck am I doing wrong? I see a lot of responses that suggest looking at the HTMX headers to determine if a partial or full page should be sent back, but I thought I could easily side-step that by using a designated api prefix like /h/* -
Passing data from frontend to backend, JS and Django
I am trying to pass data for the shipping option that a customer selects in this form: <label>Shipping option:</label> <select name="shipping_option" id="shipping_option"> <option value="">Select an option</option> {% for shipping_option in shipping_options %} <option value="{{ shipping_option.cost }}" data-id="{{shipping_option.id}}" data-cost="{{ shipping_option.cost }}" {% if selected_shipping_option == shipping_option.id %}selected{% endif %}> {{shipping_option.id}} - {{ shipping_option.name }} - £{{ shipping_option.cost }} </option> {% endfor %} </select> I am using this script which successfully logs the correct shipping_option.id: onApprove: function(data, actions) { var shippingOption = document.getElementById('shipping_option'); var selectedShippingOption = shippingOption.options[shippingOption.selectedIndex]; var shippingOptionId = selectedShippingOption.getAttribute('data-id'); var shippingOptionCost = selectedShippingOption.getAttribute('data-cost'); console.log('shippingOptionId:', shippingOptionId); return fetch('/capture_payment/', { method: 'POST', headers: { 'content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ orderID: data.orderID, shipping_option_id: shippingOptionId, shipping_option_cost: shippingOptionCost }) }).then(function(response) { return response.json(); }).then(function(captureData) { updateOrder(); }); } }).render('#paypal-button-container'); </script> I am then trying to pass this data to my update_order util which then adds the shipping_option to the order that has been placed, but i keep getting the error: KeyError: 'shipping_option': def update_order(request): data = json.loads(request.body) print('SHIPPING', data) customer = Customer.objects.get(user=request.user) order = Order.objects.filter(customer=customer, order_status='P').order_by('-id').first() transaction_id = datetime.now().timestamp() total = order.get_order_total shipping_address = ShippingAddress.objects.filter(customer=customer).order_by('-date_added').first() # Retrieve the selected shipping option from the request payload if order.order_status == 'P': order.order_status = 'C' order.transaction_id … -
The task is being received but I do not receive a notification that it has been executed
The task is being received but I don't get a notification that it is executed I want to know if the task is running import logging from celery.utils.log import get_task_logger logger = get_task_logger(name) logger.setLevel(logging.INFO) @shared_task def add(x, y): return x + y @api_view(["GET"]) def deneme(request): eta_time = datetime.now() + timedelta(minutes=1) result = add.apply_async((3,5),eta=eta_time, result=True) logger.info('Task %s succeeded in %s seconds: %s', result.task_id, result.result) return Response("Deneme") the result i expected [2023-05-04 14:09:14,515: INFO/MainProcess] Task challenge.task.add[f4a7a3dc-d774-41a3-8aa3-3a7e8f7895b2] succeeded in 0.0779999999795109s: 8 -
Access to model attributes and methods in Django 4.2 after async call for model object
How to access to model attributes and methods in Django 4.2 after async call for model object? Here is my model: class ProjectModule(models.Model): ... url = models.URLField(verbose_name="URL") ... I'm getting a coroutine with this func: async def get_module_object(module_id: int): """Get module object.""" try: return await ProjectModule.objects.aget(pk=module_id) except Exception as e: return HttpResponseServerError(f"Error: {e}") After that I query a url with next async function: async def call_url(url: str): """Make a request to an external url.""" try: async with aiohttp.ClientSession() as session: async with session.get(url=url) as response: return response except Exception as e: print(e) return web.Response(status=500) Finally in my next function I call for model and url and trying to get model object from coroutine async def htmx_test_run_module(request, module_id: int): """Test run module with HTMX request.""" if request.method == "GET": try: module_coroutine = await get_module_object(module_id=module_id) module = await module_coroutine # first error is here response = await call_url(url=module.url) response = await response_coroutine # second error is here soup = BeautifulSoup(response.text(), "lxml") tag = soup.find( module.container_html_tag, class_=module.container_html_tag_class ) return HttpResponse(tag) except Exception as e: return HttpResponseServerError(f"Error: {e}") The first error is Error: object ProjectModule can't be used in 'await' expression and the second one is Cannot find reference 'await' in 'ClientResponse | Response'. … -
when passing extra key value pair in multipartformdata that is not in modelserializer, how do to get value in validated_data after running .is_valid()
this is the test i am running @pytest.mark.django_db def test_product_creation(product_stack, client): user, token, category, subcategory, supplier, _ = product_stack subsubcategory = SubSubcategory.objects.create(title="smartphone", slug="smartphone", subcategory=subcategory) subsubcategoryattribute_color = SubSubcategoryAttribute.objects.create(attribute="color", sub_subcategory=subsubcategory) subsubcategoryattribute_processor = SubSubcategoryAttribute.objects.create(attribute="processor", sub_subcategory=subsubcategory) product_images = [] for i in range(1, 5): image_file = open(f"tests/images/product-image-{i}.webp", "rb") image = SimpleUploadedFile(f"product-image-{i}.webp", image_file.read(), content_type="image/webp") product_images.append(image) payload = { "id": user.id, "product_name": "Test Product", "description": "Test Product Description", "category": category.id, "sub_category": subcategory.id, "supplier": supplier.id, "image": product_images[0], "image2": product_images[1], "image3": product_images[2], "image4": product_images[3], "price": 1000, "slug": "test-product", "brand": "Test Brand", "minimum_order_quantity": 1, "clicks": 69, "max_price": 10000, "min_price": 1000, "variants": [ { "variant_type": "color", "price": 1234, "available": True, "image": product_images[0], "attributes": { subsubcategoryattribute_color.id: "red", subsubcategoryattribute_processor.id: "snapdragon 865", } } ] } response = client.post(reverse("submit_product_api"), payload, format="multipart", **token) print(response.data) assert response.status_code == 201 the variants is not in model so i also created a field to be validated in serializer class NewProductSerializer(serializers.ModelSerializer): variants = VariantsSerializer(many=True) class Meta: model = Products fields = ["product_name", "description", "category", "sub_category", "price", "max_price", "minimum_order_quantity", "image", "image2", "image3", "image4", "variants"] def create(self, validated_data): new_slug = slugify(validated_data['product_name']) supplier = self.context['supplier'] new_product = Products.objects.create( product_name=validated_data['product_name'], slug=new_slug, description=validated_data['description'], category=validated_data['category'], sub_category=validated_data.get('sub_category'), price=validated_data['price'], max_price=validated_data.get('max_price'), supplier=supplier, minimum_order_quantity=validated_data['minimum_order_quantity'], image=validated_data.get('image'), image2=validated_data.get('image2'), image3=validated_data.get('image3'), image4=validated_data.get('image4') ) variants = validated_data.pop('variants') for variant in variants: variant["product"] = … -
Sentry doesn't receiving any events from django app
I am trying to integrate sentry into my django app . I followed the documentation , but not getting error records/events in sentry . While making debug = True in setry_sdk.init() , I got following msg [sentry] INFO: Discarded session update because of missing release [04/May/2023 17:00:21] "GET /sentry-test/ HTTP/1.1" 500 145 [sentry] DEBUG: Sending envelope [envelope with 1 items (transaction)] project:2 host:xxxxxip [sentry] DEBUG: [Tracing] Adding sentry-trace header 7966c17f98ae45acbe2ea15edb43cxxxxxxxxxxxxxxxxxxxxx to outgoing request to http://xxxx-sentry-ip-xxxx/api/2/envelope/. I am expecting errors getting registered in sentry. -
In Django Restframework, how to create user model with profile model?
I am trying to create User with Profile on Serializer's create method. Expected input is (name, email, password). email and password will be used to create User instance and name and user instance itself will be used to create Profile instance. In UserRegisterSerializer, model is User and I defined additional field 'name' since it is not a field of User model. in create method, name is popped from validated data, and user is created with email and password. profile is created with user and name. When I test for creating user, it raise an error message 'AttributeError at /api/users/register/ Got AttributeError when attempting to get a value for field name on serializer UserRegisterSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Users instance. Original exception text was: 'Users' object has no attribute 'name'.' I don't understand it since I didn't attempt to get a value for field name. How should I fix it? What is my mistake? Views.py class UserRegisterAPIView(CreateAPIView): queryset = User.objects.all() serializer_class = UserRegisterSerializer Models.py Users : customized user that has id, email, password etc fields. Profiles : 1 to 1 linked with Users. It has user, name, etc fields. … -
How to open a form in a modal window?
Help me figure it out, please, I have a button on the page, when you click on it, a modal window opens, in which there should be a form to fill in a new record in the database, but now the modal window opens empty. views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Department from .forms import * def department_add(request): answer = '' if request.method == 'POST': form = DepartmentForm(request.POST) if form.is_valid(): form.save() else: answer = 'Error' form = DepartmentForm() data = { 'form': form, 'answer': answer } return render(request, None, data) forms.py: from django import forms from django.forms import ModelForm from .models import * class DepartmentForm(forms.ModelForm): class Meta: model = Department fields = '__all__' <button class="btn btn-success btn-add btn-padding-left" data-bs-toggle="modal" data-bs-target="#button-department-add"><i class="fa fa-plus"></i> Add department</button> <div class="modal fade" id="button-department-add" tabindex="-1" role="dialog" data-bs-backdrop="static"> <div class="modal-dialog modal-lg" role="document"> <form method="post"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="button-department-addLabel">Add department</h5> <button class="btn-close" type="button" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" style="text-align: center;"> <b>Fill and save.</b> {% csrf_token %} {{ form.as_p }} <span>{{ answer }}</span> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success btn-save"><i class="fa fa-save"></i> Save</button> <button type="button" class="btn btn-secondary btn-cancel" data-bs-dismiss="modal"><i class="fa fa-ban"></i> Cancel</button> </div> </div> </form> </div> </div> -
async delete from DB using Django 4.2 with adelete()
As per docs since v4.2 Django comes with async version of delete method named adelete(). But I do not understand how to delete an object from DB using it. db_object = await DbModel.objects.aget(pk=module_id) await db_object.adelete() # doesn't work It fails with an error: "AttributeError: 'DbModel' object has no attribute 'adelete' What is wrong? -
DRF SimpleJWT Custom claims not getting updated on token refresh
I've followed the docs to implement simple jwt, but I'm facing an issue. When I PATCH a user, and then try to refresh this user's token, the claims inside the token are outdated. The only way I can get the new claims is to logout and create a new token. This is my custom serializer: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['email'] = user.email token['name'] = user.name token['birthday'] = user.birthday.isoformat() token['reading_goal_minutes'] = user.reading_goal_minutes return token Custom view: class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer Urls: path('token/', views.MyTokenObtainPairView.as_view()), path('token/refresh/', TokenRefreshView.as_view()), Settings: from pathlib import Path from datetime import timedelta from dotenv import load_dotenv import os load_dotenv() BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') DEBUG = True ALLOWED_HOSTS = [] AUTH_USER_MODEL = 'api.UserData' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'rest_framework', 'rest_framework_simplejwt.token_blacklist', 'corsheaders', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=90), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "UPDATE_LAST_LOGIN": True, "ALGORITHM": "HS256", "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "JTI_CLAIM": "jti", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.MyTokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", … -
How to get info from multiple selection HTMX
I'm using htmx and django and i want to send information from both selections but thats not working Even if i choosed both info send only from selection that i clicked last How can i fix that? template.html <form method="get" class="w-50 custom-select"> <div class="custom-select"> <select name='ObjectGUID' class="form-select" id="select2" hx-get="{% url 'customer_contracts_for_object' %}" hx-target="#contracts_for_object"> {% for obj in all_objects %} <option {% if select_option == obj.GUID %}selected{% endif %} value="{{ obj.GUID }}">{{ obj }}</option> {% endfor %} </select> </div> <div class="custom-select"> <select name='CounterpartyGUID' class="form-select" id="select2" hx-get="{% url 'customer_contracts_for_object' %}" hx-target="#contracts_for_object"> {% for counter_party in all_counter_party %} <option {% if select_option == counter_party.GUID %}selected{% endif %} value="{{ counter_party.GUID }}">{{ counter_party }}</option> {% endfor %} </select> </div> </form> views.py current_object = self.request.GET.get('ObjectGUID') current_counter_party = self.request.GET.get('CounterpartyGUID') -
'Closing Connection' error while hosting Django application on Railway with Gunicorn Server
I am currently trying to host a Django application on Railway, but I am facing an issue in the Gunicorn server which keeps getting stuck at [DEBUG] Closing Connection. status, below are my logs. gunicorn.conf.py # Non logging stuff bind = "0.0.0.0:8000" workers = 3 # Access log - records incoming HTTP requests accesslog = "-" # Error log - records Gunicorn server goings-on errorlog = "-" # Whether to send Django output to the error log capture_output = True # How verbose the Gunicorn error logs should be loglevel = "debug" # Increase the timeout for each worker to 90 seconds timeout = 90 Railway Deployment Logs 2023-05-04 08:54:18 [1] [INFO] Starting gunicorn 18.0 2023-05-04 08:54:18 [1] [DEBUG] Arbiter booted 2023-05-04 08:54:18 [1] [INFO] Listening at: http://0.0.0.0:8000 (1) 2023-05-04 08:54:18 [1] [INFO] Using worker: sync /root/.nix-profile/lib/python3.10/os.py:1030: RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used return io.open(fd, mode, buffering, encoding, *args, **kwargs) 2023-05-04 08:54:18 [9] [INFO] Booting worker with pid: 9 2023-05-04 08:54:18 [10] [INFO] Booting worker with pid: 10 2023-05-04 08:54:18 [11] [INFO] Booting worker with pid: 11 2023-05-04 08:58:19 [9] [DEBUG] Closing connection. 2023-05-04 09:03:28 [10] [DEBUG] Closing connection. 2023-05-04 … -
How to get display value from Django Choices directly from the declared choice constant?
Lets say I defined a model class from model_utils import Choices class SomeModel(TimeStampedModel): food_choices = Choices( (1, "WATER", "Water"), (2, "BURGER", "Burger"), (3, "BIRYANI", "Biryani") ) food = models.IntegerField(choices=food_choices, default=food_choices.WATER) How do I get the display part while using the choices as a variable? eg. SomeModel.food_choices.WATER gives me 1, how do I get the value/string "Water"? I know if I create an instance, then I can fetch the display value using .get_food_display() for that instance, but I don’t want that I just want to use it directly from the constant created for Choices, ie food_choices. -
Save OpenAI streaming response after finishing stream
I have a Django API that streams responses from OpenAI. But I wan't to save the final response in my database after finishing. My code for streaming is something like this: def create_chat_message_and_stream_response_from_ai( message: str, ): def stream(): final_answer = "" data_queue = ChatService().get_stream_queue( new_message=message, ) while True: data = data_queue.get() if data == "CLOSE": ChatMessage.objects.create( message=final_answer, agent="ai", ) break final_answer += data yield data response = StreamingHttpResponse(stream()) response["Content-Type"] = "text/event-stream" return response but when I create the ChatMessage object, it raises django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I tried to add sync_to_async wrapper but now I have this error: RuntimeWarning: coroutine 'SyncToAsync.__call__' was never awaited sync_to_async(ChatMessage.objects.create)( RuntimeWarning: Enable tracemalloc to get the object allocation traceback -
Cookie cutter for packaging Django app as a python package
There is a need of creating a Django project inside a python package and later package it as a python package. Current thought : Can I use poetry-cookie cutter to create python package and django-cookie cutter for the project that is going to be used inside python package and merge them , so that the final result would be a python package. Any suggestions on this ? Would help me move ahead. -
Add a variable inside static tag for Django
The whole page is surrounded by the tag {% with page_name="course"%} {%endwith%} I need to replace this part. <link rel="stylesheet" href="{% static 'css/edit_course.css' %}"> Here comes the problem. The "course" substring can' be replaced by {{course}}. My 1st approach is: <link rel="stylesheet" href="{% static 'css/edit_' %}"{{page_name}}.css> It fiailed because the path is not complete. The result is "http://127.0.0.1:8000/static/css/edit_" The 2nd approach {% with "css/edit_"|add:"course"|add:".css" as page_css%} <link rel="stylesheet" href="{% static 'css/edit_' %}"{{page_name}}.css> {%endwith%} The error is the same. I guess the problem is the static tag can't accpet any variable. Please help, thanks. I checked some solutions on Stackoverflow. But none of them work.