Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unknown issue with Celery and Pandas (Modin), Task Execution stuck and no error
Description: I have set up a Django project with Celery and RabbitMQ in Docker. I am trying to execute a Celery task from my API viewset, and I can see the task being received in the Celery container logs. However, the task seems to get stuck when I use Pandas with Modin. Observation: Print statements above the Pandas Modin usage work fine. No error or exception is raised. Print statements after the Pandas line are not executed. Code Example: @shared_task def test_pandas_df(): print("Start task") test_df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]}) logger.info("Df Data :") print(test_df) # In my viewset: test_pandas_df.delay() Celery Container Log: My end goal is to use Pandas Modin to read a CSV Data and perform some aggregations. I have created a simple test function to understand celery task execution, But I'm unable to debug the cause of task getting stuck. I will be trying on separate Machine and using Pandas in place of Modin (although it should fallback). I'm trying to understand, Why no error or progress is shown. Kindly guide me, If I have missed something. -
Stripe split payment Django
I am working on a project where i have to split the payments for that i have connected the customer to the stripe and retrieved the stripe account number for the same class AuctionPayment(View): def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('/') else: user = request.user customer_id = user.stripe_customer_id if customer_id == "": customer_id = stripe.Customer.create(email=user.email)["id"] user.stripe_customer_id = customer_id user.save() mode = request.GET.get('mode', 'auction') auction_id = self.kwargs["auction_id"] courier_id = self.kwargs["courier_id"] if mode == 'auction': auction = Auction.objects.get(pk=auction_id) seller_id = auction.user seller_account_id = seller_id.stripe_connect_id print("-------------------------------------------------", seller_id , seller_account_id) referrals = Referral.objects.filter(referred_user=seller_id).first() referred_by = referrals.referred_by print("----------------------------------------------------refered_by ", referred_by) courier = CourierService.objects.get(auction=auction, courier_id=courier_id) if auction.current_bid is not None: price = int(round(float(auction.current_bid) * 100.0)) if auction.auction_status == "Ongoing": price = int(round(float(auction.product.nail_buy_now_price) * 100.0)) buyer_address = auction.buyer_address else: event = SpecialEvent.objects.get(pk=auction_id) courier = CourierService.objects.get(event=event, courier_id=courier_id) seller = event.selected_seller seller_request = SellerRequest.objects.get(event=event, user=seller) price = int(round(float(seller_request.price) * 100.0)) buyer_address = event.buyer_address taxes = 0 if buyer_address.state.lower() == 'alabama' or buyer_address.state.lower() == 'al': taxes = int(round(float(price * 0.08))) shipping_charges = courier.price total_charges = price + shipping_charges + taxes # if referrals: admin_amount = int((total_charges - shipping_charges) * 0.2) seller_amount = total_charges - admin_amount referral_amount = int(admin_amount * 0.02) stripe.api_key = "api_key" session = stripe.checkout.Session.create( success_url=my_domain … -
run django project on new computer
I developed a project on django for years and deployed it on heroku. Now my Computer crashed and i try to get my running django project from heroku run on my new laptop in pycharm. -i cloned my project from heroku -installed all dependencies -created new venv -set system variables secret key etc... seems like i have multiple issues... tried everything and read for hours and days but cant get it working .... any tip would be usefull Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\schno\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\schno\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\urls\resolvers.py", line 416, in check for pattern in self.url_patterns: File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\urls\resolvers.py", line 602, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\urls\resolvers.py", line 595, in … -
Can't figure out why my DRF login test is not working as expected
I have the following test case: class CustomUserViewSetTests(APITestCase): @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create( email="test@email.com", password="testpass123" ) def test_login_with_correct_data(self): url = reverse("knox_login") resp = self.client.post( url, data={ "email": "test@email.com", "password": "testpass123", }, format="json", ) respJson = resp.json() self.assertEqual(resp.status_code, status.HTTP_200_OK) The test always fails since "resp" has a 400 status code with body {'non_field_errors': ['Unable to log in with provided credentials.']}. When I check the test database via get_user_model().objects.all(), I can see that the user exists. Also, when I call the url via Postman, I get status code 200 with token and user details returned in body. -
Add javascript to rendered html streamfields
I am using streamfields in my wagtail project and I want to add js to rendered templates I tried like this: enter image description here But it does not append to the end of the body like in page templates, any ideia how can i enter image description here I have tried this and also StructBlockAdapter but none of that works, StructBlockAdapter only adds JS to backoffice -
I am getting multivalue key error in views in django
I created a Review System When I am going to submit the review there is an error In my views.py: def ajex_add_review(request,pid): product=Product.objects.get(pk=pid) user=request.user review=ProductReview.objects.create( user=user, product=product, review=request.POST['review'],#1 rating=request.POST['rating'],#2 ) context={ 'user':user.username, 'review':request.POST['review'],#1 'rating':request.POST['rating'],#2 } average_reviews=ProductReview.objects.filter(product=product).aggregate(rating=Avg("rating")) return JsonResponse( { 'bool':True, 'context':context, 'average_reviews':average_reviews, } ) I think that the error coming from here. Because if I comment out review(#1) or rating(#2) any of this it is working perfectly well In case if you need my js file then In function.js: console.log("working"); $("#commentForm").submit(function(e){ e.preventDefault(); $.ajex({ data: $(this).serialize(), method: $(this).attr("method"), url: $(this).attr("action"), dataType: "json", success: function(response){ console.log("Comment Saved"); } }) }) and In my product-detail.html <div class="add-review"> <h3>Add Your Review</h3> <form action="{% url 'core:ajex_add_review' p.id %}" method="POST" id="commentForm"> {% csrf_token %} {{review_form.rating}} </form> <br> <form action="{% url 'core:ajex_add_review' p.id %}" method="POST" id="commentForm"> {% csrf_token %} {{review_form.review}} <button type="submit" class="btn">Submit</button> </form> <div class="rating-bar"> <div class="bar"> <div class="fill" style="width: 80%;"></div> </div> <div class="bar-label"><i>{{average_rating.rating|floatformat:1}} out of 5.0</i></div> </div> </div> So please help me out from this problem. And my Indentation are correct. And at last My error is: System check identified 2 issues (0 silenced). March 08, 2024 - 01:45:45 Django version 4.1.13, using settings 'ecomprj.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. … -
A Profile to make Detailed changes in Django Rest-Framework API. I have created Serializered File and View file but Detail is not saved
Actually, I am working on a project and I have to modify the authentication system so that I am able to log in using username and password. I have Login Successfully and I have Change Detail but Don't Change Detail. Please Solve This Code and give me a Code. My serializrs.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ("first_name", ) def create(self, validated_data): user_id = Token.objects.get(key=validated_data.auth.key).user_id user = User.objects.get(id=user_id) first_name = validated_data.get('first_name') user.first_name = first_name user.save() return user My views.py class ProfileAPIView(APIView): serializer_class = ProfileSerializer permission_classes = [permissions.AllowAny] authentication_classes = [TokenAuthentication] def post(self, request): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(raise_exception=True): return Response({"msg":"Profile Update"}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) Solve this Serialize File And View File and Give me a Code. -
How to customize lockout mechanism in Django Axes?
I am new to Django Axes. I need to customize the lockout of Django Axes so that the user is locked out when the number of login attempts reaches the AXES_FAILURE_LIMIT within a 10 minute period. I tried creating a custom handler for the signal user_login_failed that: Gets the list of Access Attempts of the username Gets the time difference of the oldest and the latest login attempt If the login attempts count are less than or equal to the AXES_FAILURE_LIMIT, and if the time difference is more than 10 minutes, It will delete the oldest attempt to prevent the lockout. Else, it will continue the lockout process. However, when the login attempt reaches the AXES_FAILURE_LIMIT, the user_login_failed signal is not triggered and the user is locked out. Is there a better way to handle this? Is this just a configuration on Django Axes? -
MIME type error with css file and load static showing in plain text - Django on PyCharm IDE
In my HTML template, when I pass it to debug mode, gets the following errors: Refused to apply style from its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.; MIME Error {% load static %}` shows in plain text; Pics and css files are in YouTrade1/static/YouTrade1 Template is in YouTrade1/templates/YouTrade1 I tried several solutions for the documentation of my static files and none seem to work. All documentation according to Django best practices. I don't manage to understand whether there's something wrong with either my django project setup (which looks fine), my testing environment (I click debug/run on pyCharm IDE and they said it's all fine on their side) or my HTML script. Css File HTML page Settings1 Settings2 URLs Views -
Django - GenericForeignKey with BaseDatatableView
I'm having trouble using a generic foreign key in BaseDatatableView. Hello. I decided to use a generic foreign key in django. In orm I can do what I need, I can go through content_object to the instance that is connected to this field and easily read the field values of this instance. The problem occurs when I create tables using BaseDatatableView. [models.py] class Warehouse(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') quantity = models.IntegerField() def __str__(self): return f'{self.content_object.name} - {self.quantity}' class Meta: indexes = [ models.Index(fields=['content_type', 'object_id']) ] class Product1(models.Model): name = models.CharField(max_length=50) tag = models.SlugField() note = models.CharField(max_length=20) def __str__(self): return self.tag class Product2(models.Model): name = models.CharField(max_length=50) tag = models.SlugField() note = models.CharField(max_length=20) def __str__(self): return self.tag ( The model architecture is exemplary and only tests relationships ) [table.py] class Product1WarehouseDataTable(BaseDatatableView): model = Warehouse columns = ['content_object__name', 'content_object__tag', 'content_object__note', 'quantity'] def get_initial_queryset(self): ct = ContentType.objects.get_for_model(Product1) qs = self.model.objects.filter(content_type=ct) return qs BaseDatatableView throws an error: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. I want to display data from Product 1 in the table from the Warehouse model. … -
Django CORS configuration not working despite middleware setup
I'm encountering an issue with CORS (Cross-Origin Resource Sharing) configuration in my Django project. Despite configuring CORS settings in my settings.py and adding the CorsMiddleware to the MIDDLEWARE list, I still encounter CORS-related errors when making requests from my frontend application. Here's a summary of my configuration: settings.py (CORS and CSRF settings): # CORS CORS_URLS_REGEX = r"^/api/.*$" CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = config("CORS_ORIGIN_WHITELIST", cast=Csv(), default=["http://localhost:3000"]) CORS_ALLOWED_ORIGINS = config("CORS_ALLOWED_ORIGINS", cast=Csv(), default=["localhost:3000"]) CORS_ALLOW_ALL_ORIGINS = config("CORS_ALLOW_ALL_ORIGINS", default=True, cast=bool) CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) CORS_ALLOW_HEADERS = list(default_headers) + ["Set-Cookie"] # CSRF CSRF_TRUSTED_ORIGINS = config("CSRF_TRUSTED_ORIGINS", cast=Csv()) CSRF_USE_SESSIONS = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_SAMESITE = None settings.py (MIDDLEWARE): MIDDLEWARE = ( "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) Despite having these settings in place, when I attempt to make a request from my frontend application (https://example.com) to my Django backend (https://api.example.com/api/v1/), I receive the following error: Access to XMLHttpRequest at 'https://api.example.com/api/v1/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Failed to load resource: net::ERR_FAILED Also I get this result from Postman: Django version: 4.2.1 django-cors-headers version: 4.3.1 -
Django How to save image on my custom path when triggering signals
When I trigger this signal, the image is copied from my ImageModel and uploaded to my OrderItem model in the order_image_file field. The product image is being saved to its original ImageModel destination even though I have defined a custom path in my OrderItem model. def orderImage_upload_path(instance, filename): return f'order_image/{generate_sku()}_{filename}' class OrderItem(models.Model): product_image = models.ForeignKey(ProductImage, on_delete=models.SET_NULL,blank=True,null=True) order_image_file = models.ImageField(blank=True,null=True,upload_to=orderImage_upload_path) my signals @receiver(post_save, sender=OrderItem) def OrderItem_Signals(sender,created ,instance, **kwargs): if created: if not instance.order_image_file and instance.product_image: instance.order_image_file = instance.product_image.image instance.save() -
Passing instances to both model forms, one's model object is updated but about the next, a new object is made
I want to edit both a Drug object and a Bgt object; so I have used Django model forms and have passed instances of both models to it in view. It updates the Bgt object, but Drug object is not updated; instead a new Drug object is made, why? the relationship among both models: Bgt model has a drug field which is a foreignKey field to Drug In this image, 'kostery' was the previous bgt object, which is now changed to 'kostery3' But in the second image, Drug 'Kostery' still exists and a new Drug is created 'Kostery3' View function: The following image is view function: the following is bgt Edit form: this is the drug edit form: this is drug model: -
Django how to use post_save for upload image from another model
I am trying to copy image from my ProductImage models and upload it to my OrderItem models when any new order items will be crate but got this error AttributeError: 'NoneType' object has no attribute 'image' but you can see my ProductImage model have image fields. here my two models: #ProductImage Model class ProductImage(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE,blank=True,null=True) image = models.ImageField(upload_to=dynamic_upload_path) thumb_image = models.ImageField(upload_to=dynamic_upload_path,blank=True,null=True) #OrderItem models class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL,blank=True,null=True) product_image = models.ForeignKey(ProductImage, on_delete=models.SET_NULL,blank=True,null=True) order_image_file = models.ImageField(blank=True,null=True,upload_to=orderImage_upload_path) my signals: @receiver(post_save, sender=OrderItem) def OrderItemSignals(sender, instance, created,**kwargs): if created: instance.order_image_file = instance.product_image.image so basically when any order item will be crate I want to fire my post save for copy image from my product image models and upload it to my order item models image fields. -
The Like button does not change to Dislike, Django
When a user puts a Like, the reverse Dislike button should be displayed, but this does not happen. If you remove the if condition, then like and dislike work separately, the data is written to the database and deleted accordingly. But there is a problem with the if condition. When the user has already put a Like, the information is not taken from the database that they need to put a Dislike instead of a Like. Do not understand why. models.py: class PostLike(models.Model): userlikepost = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) likepost = models.ForeignKey(Userpublication, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('userlikepost', 'likepost') views.py: def show_post(request, post_slug): post = get_object_or_404(Userpublication, slug=post_slug) like_count = PostLike.objects.filter(likepost=post).count() liked_by_current_user = False if request.user.is_authenticated: liked_by_current_user = PostLike.objects.filter(likepost=post, userlikepost=request.user).exists() print(f'liked_by_current_user: {liked_by_current_user}') context = { 'post': post, 'like_count': like_count, 'liked_by_current_user': liked_by_current_user, } return render(request, 'pie/home.html', context) @login_required def like_post(request, post_id): try: post = Userpublication.objects.get(pk=post_id) like, created = PostLike.objects.get_or_create(userlikepost=request.user, likepost=post) like_count = PostLike.objects.filter(likepost=post).count() like_count = PostLike.objects.filter(likepost=post).aggregate(count=Count('id'))['count'] return JsonResponse({'liked': created, 'like_count': like_count}) except Exception as e: return JsonResponse({'error': str(e)}, status=500) @login_required def unlike_post(request, post_id): try: post = Userpublication.objects.get(pk=post_id) like = PostLike.objects.filter(userlikepost=request.user, likepost=post).first() if like: like.delete() like_count = PostLike.objects.filter(likepost=post).count() return JsonResponse({'unliked': True, 'like_count': like_count}) except Exception as e: return JsonResponse({'error': str(e)}, status=500) html: … -
I got an error when i tried to deploy my django app on vercel
I build my app on django, with all my dependencies especified on file "requirements.txt" i didn't make an enviroment on vercel to deploy cause i saw a tutorial where the man didn't it. I have tow files called: build_files.sh and vercel.json build_files.sh: pip install -r requirements.txt python3 manage.py collectstatic --noinput vercel.json: { "version": 2, "builds": [ { "src": "gestor_backend/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.8" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "gestor_backend/wsgi.py" } ] } requirements.txt: asgiref==3.7.2 backports.zoneinfo==0.2.1 certifi==2024.2.2 cffi==1.16.0 charset-normalizer==3.3.2 cryptography==42.0.5 defusedxml==0.8.0rc2 Django==4.2 django-cors-headers==4.3.1 django-templated-mail==1.1.1 djangorestframework==3.14.0 djangorestframework-simplejwt==5.3.1 djoser==2.2.2 idna==3.6 mysqlclient==2.2.4 oauthlib==3.2.2 pycparser==2.21 PyJWT==2.8.0 python3-openid==3.2.0 pytz==2023.3.post1 requests==2.31.0 requests-oauthlib==1.3.1 social-auth-app-django==5.4.0 social-auth-core==4.5.3 sqlparse==0.4.4 typing_extensions==4.9.0 tzdata==2023.4 urllib3==2.2.1 this is the entire error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Trying pkg-config --exists libmariadb Command 'pkg-config --exists libmariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, … -
How to integrate real-time computer vision code to django
I have this code for real-time action detection using MediaPipe and a deep learning model. I want to create a Django video streaming web app and integrate this code to detect actions from the frames. I have tried putting the entire code in a class (along with the function definitions of each function called in the code) in a separate python script (camera.py). I then imported the entire class into my views.py but the frames don't show when I run the server. This is the code I would like to integrate into the Django app: sequence = [] sentence = [] predictions = [] threshold = 0.5 cap = cv2.VideoCapture(0) # Set mediapipe model with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic: while cap.isOpened(): # Read feed ret, frame = cap.read() # Make detections image, results = mediapipe_detection(frame, holistic) print(results) # Draw landmarks draw_styled_landmarks(image, results) # 2. Prediction logic keypoints = extract_keypoints(results) sequence.append(keypoints) sequence = sequence[-30:] if len(sequence) == 30: res = model.predict(np.expand_dims(sequence, axis=0))[0] print(actions[np.argmax(res)]) predictions.append(np.argmax(res)) #3. Viz logic if np.unique(predictions[-10:])[0]==np.argmax(res): if res[np.argmax(res)] > threshold: if len(sentence) > 0: if actions[np.argmax(res)] != sentence[-1]: sentence.append(actions[np.argmax(res)]) else: sentence.append(actions[np.argmax(res)]) if len(sentence) > 5: sentence = sentence[-5:] # Viz probabilities image = prob_viz(res, actions, image, colors) cv2.rectangle(image, … -
How can I add customized CSS styles to django-ckeditor editor?
I wanna be able to add customized CSS styles that I've already defined on my CSS files. I read the documentation here and here, but it just does not work. **django-ckeditor version ** django-ckeditor 6.7.1 This is ckeditor configs CKEDITOR_CONFIGS = { 'default': { 'allowedContent': True, 'stylesSet':[ { 'name':'highlighted-text', 'element':'div', 'attributes':{'class':'highlighted-text'} }, ], 'toolbar': 'Custom', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink'], ['RemoveFormat', 'Source', 'Image', 'Table'] ], } } **This is how django-ckeditor is looking like ** Any thoughts? -
TypeError: Improper geometry input type: <class 'dict'>
I have this django model: from django.contrib.gis.db import models from django.contrib.gis.forms import PolygonField class Field(models.Model): boundary = PolygonField(srid=4326) asset_id = models.CharField(max_length=255, unique=True) Given a polygon, I need to check its intersections with what's in the database. So I do: from django.contrib.gis.geos import GEOSGeometry polygon = { 'type': 'Polygon', 'coordinates': [ [-72.35720634789077, 47.72858763003908], [-71.86027854004486, 47.52764829163817], [-72.37075892446839, 47.539848426151735], [-72.35720634789077, 47.72858763003908], ], } Field.objects.filter(boundary__intersects=GEOSGeometry(polygon)) and I get: GEOSGeometry(polygon) Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/IPython/core/interactiveshell.py", line 3508, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-16-a799be749a02>", line 1, in <module> GEOSGeometry(polygon) File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/geos/geometry.py", line 767, in __init__ raise TypeError("Improper geometry input type: %s" % type(geo_input)) TypeError: Improper geometry input type: <class 'dict'> What is the proper way of achieving this? I also tried this: >>> Field.objects.filter(boundary__intersects=GEOSGeometry(json.dumps(polygon))) Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/IPython/core/interactiveshell.py", line 3508, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-3-155b1b25302f>", line 1, in <module> Field.objects.filter(boundary__intersects=GEOSGeometry(json.dumps(polygon))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/geos/geometry.py", line 753, in __init__ ogr = gdal.OGRGeometry.from_json(geo_input) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/gdal/geometries.py", line 167, in from_json return OGRGeometry(OGRGeometry._from_json(force_bytes(geom_input))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/gdal/geometries.py", line 154, in _from_json return capi.from_json(geom_input) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/gis/gdal/prototypes/errcheck.py", line 83, in check_geom raise GDALException( django.contrib.gis.gdal.error.GDALException: Invalid geometry pointer returned from "OGR_G_CreateGeometryFromJson". more details -
How to properly send response to React Frontend from Django Channels?
I am trying to use Django Channels to implement long-polling for a React frontend web app and Django REST backend. I believe that much of what I have is working to some degree, but some thing(s) must be incorrectly configured or coded to produce unexpected results. In short, the problem that I am receiving is that when the Django Channels Consumer sends back a response, it does not immediately go back to the frontend (per console.log(...)s in the code); rather, it seems the Consumer must send another response and then the previous or both responses appear in the frontend. I am trying to implement using AsyncHttpConsumer because Websockets are not possible in our use-case. Asgi.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": URLRouter( longpoll_urlpatterns + [re_path(r"", django_asgi_app)] ), } ) Routing.py longpoll_urlpatterns = [ # Tried using re_path but did not work path("analysisSubscription/<int:analysisId>/", consumers.AnalysisConsumer.as_asgi()), ] Consumers.py class AnalysisConsumer(AsyncHttpConsumer): async def handle(self, body): print("In Handle") print(self.scope) self.analysisId = self.scope["url_route"]["kwargs"]["analysisId"] self.analysis_group_name = f"analysis_{self.analysisId}" # Register with the appropriate channel await self.channel_layer.group_add(self.analysis_group_name, self.channel_name) await self.send_headers(headers=[ (b"Content-type", b"application/json"), (b"Access-Control-Allow-Origin", b"*"), (b"Access-Control-Allow-Headers", b"Origin, X-Requested-With, Content-Type, Accept, Authorization"),]) #The server won't send the headers unless we start sending the body await self.send_body(b"", more_body=True) … -
Django template svg rendering issue
I have a django html template that contains this svg element: <svg id="tower_layout" width="400" height="400" style="border: 1px solid black;" xmlns="http://www.w3.org/2000/svg"> <rect width="398" height="398" x="1" y="1" fill="#e4e4e7" /> <text x="200" y="20" stroke="black" font-size="15" text-anchor="middle">Tower Diagram</text> {% for i in val_range %} {% if i > 0 %} <line x1="{{ val[i-1].x_d }}" y1="{{ val[i-1].y_d }}" x2="{{ val[i].x_d }}" y2="{{ val[i].y_d }}" stroke-width="1" stroke="black" /> {% endif %} {% endfor %} I'm receiving "TemplateSyntaxError: Could not parse the remainder: '[i-1].x_d' from 'val[i-1].x_d'" when I try to render the template. I've paused the template and verified that all 4 val items are available using the debug console. I'm baffled as to the cause of this error. Any suggestions would be much appreciated! -
How to fix a url submit_function not working?
trying to make a rating system but i get this errorerror, here are my urls and views urls views i want it to send ratings into the database when rating is sent -
Cannot autopopulate date field in django template with widget_tweaks
I’m building a django app that basically is a service for legal guardians to automatically create invoices. For the necessary information about their patients that need to be printed on the invoice, I have a model Patient: class Patient(models.Model): address_as = models.ForeignKey('AddressAs', on_delete=models.PROTECT) first_name = models.CharField('First Name', max_length=120) last_name = models.CharField('Last Name', max_length=120) birthday = models.DateField('Birthday') guardian = models.ForeignKey('Guardian', on_delete=models.CASCADE) court = models.ForeignKey(Court, related_name='patients', on_delete=models.PROTECT) record_number = models.CharField('Record Number', max_length=50) first_billing_date = models.DateField('Start of Legal Care', null=True, blank=True) billing_start = models.DateField('Start of Billing', null=True, blank=True) billing_end = models.DateField('End of Billing', null=True, blank=True) last_billing = models.DateField('Last Billing Date', null=True, blank=True) dutyscope_financial = models.BooleanField('Dutyscope Financial Care') is_wealthy = models.BooleanField('Patient is wealthy', default=False) taken_from_volunteer = models.BooleanField('Taken from Volunteer', default=False) given_to_volunteer = models.BooleanField('Given to Volunteer', default=False) def __str__(self): return f'{self.last_name}, {self.first_name}, geb. {self.birthday}' and a very simple form class: class PatientForm(forms.ModelForm): class Meta: model = Patient fields ='__all__' and of course a view to create patients and a template. So far, so good. Everything works. But now I want to add the possibility to edit the patient’s data. I created a new view for that: def edit_patient(request, patient_id): patient = Patient.objects.get(id=patient_id) if request.method =='POST': form = PatientForm(request.POST or None, instance=patient) if form.is_valid(): updated_patient = … -
pandas read_sql using Django.db.connection
Is there a recommended way to utilize pandas read_sql from within a Django app? I was using a much older version of pandas and this worked: import django.db.connection import pandas as pd df = pd.read_sql("select employee.name from employee;", con=connection) Now, I'm getting this error from read_sql: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy. The query seems to work even with the warning but I don't want to take chances that it might break. I was using the Django.db.connection so that pandas makes use of the db connection pooling within Django. I can successfully use a connection string with the read_sql method but I don't want pandas opening up a bunch of connections in a multi-user system. Same with SQLAlchemy - I don't want to add another connection pool into the app. Any advice or workarounds? I haven't found anything in the pandas or Django documentation covering this. Django==3.2 pandas==2.2.1 mysqlclient==2.2.4 MySQL version 8 -
Is there a way to have SSO using Atlassian for our external Django application?
We created a Forge app and we have an existing Django/Python application. Our forge app app has a connect button and when the user clicks it we want the user to automatically login with the credentials from Jira. Is there a way of possibly doing that? We followed Django-OAuth-Toolkit documentation to build an OAuth 2.0 provider. We managed to get our access token using bash. We followed the documentation on the Atlassian website for External OAuth 2.0 for Forge apps. But we could not get that working. We were expecting some type of response using the Google provider but kept getting errors. We aren't sure exactly what to do after this. The documentation vague.