Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
GET /student HTTP/1.1" 200 2 Django
i am beginner to django i have created new project project. when i run the project yesterday worked successfully. if i tried today i ran into the problem with i attached complete stacktrace below. when view the records type api http://127.0.0.1:8000/student then Api display as [] just black see the error on console look like this System check identified no issues (0 silenced). May 04, 2023 - 13:39:40 Django version 3.2, using settings 'SchoolProject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [04/May/2023 13:39:46] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:46] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:47] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:47] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:47] "GET /student HTTP/1.1" 200 2 [04/May/2023 13:39:47] "GET /student HTTP/1.1" 200 2 -
Why does my React website open in Safari but not in Chrome. The IP address works on both browsers, however the domain only works on one
I pointed a domain (www.mynacode.com) to my AWS instance IP address (34.228.112.169) running my django+react website. The IP address works fine and my website loads on all browsers. However, when I use the domain mynacode.com, my website only opens up on Safari and Mozilla, but not on Chrome. On Chrome, it gives an error: This site can't be reached. Is there a reason why it doesn't work on Chrome. I've cleared the cache, tried opening in incognito mode and even tried it on another laptop but it still won't open in Chrome. -
get all values of same row name in a list in django
[img2] img1 what i want is Apple-[Jessica,mathewo,Anthony] etc etc for each company queryset1 = (Company.objects.values('name',).annotate(total=Count('employeename'),).order_by()) gives me image1, it gives me total number of employee each company has but not values in detail. companies = Company.objects.all() img2 gives me id of company which i need, and all informaton but in seprate rows, not as a list {% for company in companies %} <tr> <td>{{ company.name }} <a href="{% url 'api:form_view' company.id %}">(Add Employee)</a></td> <td>{{ company.id }}</td> <td>{{ company.employeename }}</td> </tr> {% endfor class Employee(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) comment = models.TextField() #companyname=models.OneToOneField(Insert, on_delete=models.CASCADE) def __str__(self): return f"{self.first_name} {self.last_name}" class Company(models.Model): name = models.CharField(max_length=100) #newuser= models.ForeignKey(Employee, on_delete=models.CASCADE) employeename = models.OneToOneField(Employee, on_delete=models.CASCADE,null=True) -
Can't import app in project URL in Django
I can't import app in project (Django rest framework) URL (urls.py) in a Django project. I have done this same scenario in one of my projects in past. from appname import views This is what I need. When I trying to provide the first letter of my app name in previous project (like from a) it is giving full app name (from appname) but in new project it won't getting. I know there have other options to overcome this. But I need to know the reason behind this. making the project directory as source directory is the only solution for this? If we doing like this if there any problem, while hosting the project in server? Please someone help. I need to import app view in my project URL. -
Drawing polylines on OSM near edges is tricky, How can I get rid of these horizontal lines?
enter image description here I am trying to draw a track that satellite follows when revolving around earth. I used Open Street Maps for it and Leafletjs to integrate it with my web app. Snippet of the JS. var trackList15 = [] for (let trackPoint of tracks ) { trackList15.push([trackPoint.latitude, trackPoint.longitude]) } When it is close to the edges of the map a horizontal line is drawn to connect the visually apart points on the map. I want to discontinue the line at the edge and draw new one from the other edge. I haven't been able to find a way to detect edges of the map to discontinue the polyline when it is near edges -
Include with tags dynamic value in django
I'm confused about how can I assign dynamic value to custom_variable using include with in Django based on the click button it is possible? I just want to show the modal based on the clicked button {% include "modal_main.html" with custom_variable="dynamic_variable" %} <button type="button" class="btn btn-label-primary button_orange">Orange</button> <button type="button" class="btn btn-label-primary button_mango">Mango</button> <script> $(document).ready(function(){ $('.button_orange').click(function (event) { //pass data to custom_variable which is value of orange }); $('.button_mango').click(function (event) { //pass data to custom_variable which is value of mango }); }); -
created_by and updated_by fields in Models.py
how to implement created_by and updated_by fields in my models.py and also when do i pass models.created_by and updated_by == request.user in my views.py? please can anyone help me to do from scratch -
Django basic form submits successfully, but it doesn't update the datebase
As a test run after reading through Django for Beginners, I am trying to make a server with custom D&D character sheets. Here is my the relevant fields in my model (keep in mind that I have other fields, I just didn't list them for simplicity): from django.db import models from django.urls import reverse from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as gtl import json class charSheet(models.Model): # character's name char_name = models.CharField(max_length=45) # player's name which is the key that will # group together different character sheets # together author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) Here is my forms.py: from django import forms from .models import charSheet class CharacterForm(forms.ModelForm): class Meta: model = charSheet # fields = [field.name for field in charSheet._meta.get_fields() if field.name != "author"] # fields = "__all__" fields = ["char_name", "author"] and the relevant part of my views.py class CharacterCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = charSheet template_name = "character_new.html" fields = [ field.name for field in charSheet._meta.get_fields() if field.name != "author" ] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): obj = self.get_object() return obj.author == self.request.user Here is my urls.py rom django.urls import path from .views import ( CharacterListView, … -
How to call api(post method) into html template using Vue Js? Is this right way to pass data? [closed]
created(){ this.sku= '{{sku}}' axios.post('http://url/api/'+ this.sku +'/reports/report', {headers: { Authorization: 'Bearer '+token}}, {data:{from_date: '2023-05-01', to_date: '2023-05-30'}}) .then(response =>{ console.log(response.data.data) this.total_sale = response.data.total_sale, this.total_purchases = response.data.total_purchases, this.total_expenses = response.data.total_expenses, this.sales_total_profit = response.data.sales_total_profit }) } I am getting API(get method) data using the same way into html template on the script tag but post-method API data can't. Is there any wrong with my code? -
How to build bulk E-mail sender web application
I am trying to create bulk E-mail sender web application like SendGrid, but I am confused about how I can do this without using any APIs. I would like to create my own API, so please help me if anyone knows how to do it. Specifically, I am interested in creating a bulk E-mail sender web application in Python/Django. I am trying to create web application like SendGrid Without any APIs. -
Django project prectice
As a college student practicing Django and DRF, i have theoretical knowledge but lack industrial experience. While internships can be a great way to gain practical experience, is there any other ways to practice solving DRF problems. to participate python there are lots of online coding challenges or competitions focused on Websites such as HackerRank, LeetCode, and CodeSignal offer coding challenges in a variety of programming languages, is there any for Django & DRF ? i have watched tutorials and alots of stuff , i need raal probles facing in real problems -
How can I change numbers in a url parameter in Django Template?
I'm trying to make a pagination system. I want to change a number in a url parameter. The URL is like this; https://example.com?page=1 What I'm trying in a template is below, but it doesn't work. <a class="next_page" rel="next" href="{{request.build_absolute_uri|cut:'&page={{current_page}}'}}page={{current_page|add:1}}">Next</a> I'm passing current_page variable from view.py and remove the old page number from the url parameter and then giving the new number. The problem is I can't use current_page variable in the cut filter. How should I resolve the problem?