Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't "test" amazon alexa custom skill in the developer console
I'm trying to develop a simple notification custom skill served on a web service using "django-ask-sdk". On the "build" tab, all the "Building Your Skill" categories are green: Invocation Name: OK Intents, Samples, and Slots: OK Build Model: OK Endpoint: OK On the "test" tab, "skill testing is enabled in" is set to "Development". On the "test" tab, in the "Alexa Simulator", it appears that I can issue a request, but the response is, "The requested skill can't be accessed". I'm using "HTTPS" endpoint type, and the endpoint set for the "Default Region" is correct. I'm not seeing any request being sent to my endpoint. Am I missing some configuration, or am I not understanding how the test tab works? How can I get a test request sent to my web skill? -
Looking for budget friendly hosting options for Django backend
I live in Turkey and plan to use Django for my backend. I’ve never rented hosting before and am looking for an affordable option that works well with Django. If you have any recommendations for reliable and budget-friendly hosting providers, I’d really appreciate your suggestions. I looked into hosting providers that support Django and compared their plans, but I haven’t been able to find a suitable and affordable option yet. -
Django Management Command Not Triggering API Update in Frontend: Debugging Connection Issues Between Django Backend and React Frontend
from django.core.management.base import BaseCommand from myapi.models import StrengthWknes, CustomUser import pandas as pd from sklearn.neighbors import NearestNeighbors from sklearn.linear_model import LinearRegression import numpy as np class Command(BaseCommand): help = 'Create study groups based on normalized percentages using k-NN and predict target score for the weakest subject' def add_arguments(self, parser): parser.add_argument('grade', type=str, help='Grade for which to create study groups') parser.add_argument('current_user_id', type=int, help='ID of the current user') parser.add_argument('n_neighbors', type=int, default=5, help='Number of neighbors to find') def handle(self, *args, **kwargs): grade = kwargs['grade'] current_user_id = kwargs['current_user_id'] n_neighbors = kwargs['n_neighbors'] user_data = self.fetch_user_data(grade) group_usernames, group_df = self.create_study_group(user_data, current_user_id, n_neighbors) if len(group_usernames) < 3: self.stdout.write(self.style.WARNING('Group is too small. Select group manually.')) else: self.stdout.write(self.style.SUCCESS(f'Created group: {group_usernames}')) # Predict target score for the weakest subject if not group_df.empty: target_scores = self.predict_target_score(group_df, current_user_id) self.stdout.write(self.style.SUCCESS(f'Target scores for the weakest subject: {target_scores}')) def fetch_user_data(self, grade): records = StrengthWknes.objects.filter(grade__grade=grade) data = [] for record in records: user = CustomUser.objects.get(pk=record.id.id) data.append({ 'user_id': user.id, 'username': user.username, 'normalized_percentage': record.normalized_percentage, 'strgth_wkness': record.strgth_wkness }) df = pd.DataFrame(data) self.stdout.write(self.style.SUCCESS(f'Fetched user data:\n{df}')) return df def create_study_group(self, df, current_user_id, n_neighbors): TOLERANCE = 10 # Tolerance percentage range for neighbor selection MAX_DIFF = 10 # Maximum allowed difference within the group if len(df) < n_neighbors: return [], pd.DataFrame() # Return … -
Can't access the Django endpoints
Can't access the various Django endpoints. Tried accessing the endpoints such as http://127.0.0.1:8000/api/line-chart-data/ http://127.0.0.1:8000/api/candlestick-data/ and etc, but got a 404. urls.py """ URL configuration for mysite project. The `urlpatterns` list routes URLs to For more information please see: https://docs.djangoproject.com/en/5.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ # mysite/urls.py from django.contrib import admin from django.urls import path from .views import line_chart_data, candlestick_data, bar_chart_data, pie_chart_data from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('charts.urls')), path('api/candlestick-data/', candlestick_data), path('api/line-chart-data/', line_chart_data), path('api/bar-chart-data/', bar_chart_data), path('api/pie-chart-data/', pie_chart_data), ] views.py # mysite/views.py from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def candlestick_data(request): data = { "data": [ {"x": "2023-01-01", "open": 30, "high": 40, "low": 25, "close": 35}, {"x": "2023-01-02", "open": 35, "high": 45, "low": 30, "close": 40}, ] } return Response(data) @api_view(['GET']) def line_chart_data(request): data = { "labels": ["Jan", "Feb", "Mar", "Apr"], "data": [10, 20, 30, 40] } return Response(data) … -
TypeError: ‘NoneType’ object is not iterable
when testing a site using pytest, I get an error in the test, and I can’t figure out what is causing the error, please tell me where exactly the problem is in my code, and how to fix it (Files with tests cannot be changed - pytest). My code views.py: from django.views.generic import ( CreateView, DeleteView, DetailView, ListView, UpdateView ) from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.contrib.auth.forms import PasswordChangeForm from django.urls import reverse_lazy from django.contrib.auth import update_session_auth_hash from django.contrib.auth.mixins import UserPassesTestMixin from blog.models import Category, Post from .models import Comment from .forms import CommentForm from .forms import PostForm from .forms import UserProfileForm User = get_user_model() class OnlyAuthorMixin(UserPassesTestMixin): def test_func(self): object = self.get_object() return object.author == self.request.user class PostListView(ListView): model = Post queryset = ( Post.published .order_by('-pub_date') ) paginate_by = 10 template_name = 'blog/index.html' class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm template_name = 'blog/create.html' def get_success_url(self): return reverse_lazy( 'blog:profile', kwargs={'username': self.request.user.username} ) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostDetailView(DetailView): model = Post template_name = 'blog/detail.html' context_object_name = 'post' def get_object(self, queryset=None): post_id = self.kwargs.get("post_id") return get_object_or_404(Post, pk=post_id) def get_context_data(self, … -
change_form.html cannot display any drop-down select fields for the ModelForm
I'm working on implementing a drop-down menu for the "add" page of Product_to_Stock_Proxy_Admin function in the Django admin interface. The options for the drop-down menu are from the Distributor model, which is a foreign key for the Product model. The output only shows the drop-down menu itself, and there are no values from the Distributor model, not even the default value "---------". I don't understand why this is happening. Sincerely thank you for your help and suggestions. The reason why I use change_form is because I use Ajax to display other columns immediately when the user fills in the barcode_number. Therefore, I need to implement the drop-down menu on my own. models.py class Product(models.Model): name = models.CharField(max_length=20, blank=True, null=True) distributor = models.ForeignKey('Distributor', on_delete=models.CASCADE) barcode_number = models.CharField(max_length=20, blank=True, null=True) total_amount = models.IntegerField(blank=True, null=True) class Distributor(models.Model): name = models.CharField(max_length=10) admin.py class Product_to_Stock_Proxy_Admin(admin.ModelAdmin): form = Product_to_Stock_Proxy_Form change_form_template = 'admin/change_form.html' fields = ["distributor", "name", "total_amount"] admin/change_form.html This code only displays the drop-down item itself without any options, not even the default value "-------": {% block content %} <form method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row field-barcode_number"> <div> <div class="flex-container"> <label for="id_barcode_number">條碼號碼:</label> <input type="text" id="id_barcode_number" name="barcode_number" value="{{ form.barcode_number.value }}" /> </div> </div> </div> … -
Angular proxy not working with Django allauth
I have an angular + django project and mostly everything is working. I've setup a proxy.conf as mentioned in the documenation - example here: { "/api": { "target": "http://localhost:8000", "secure": false, "logLevel": "debug", "changeOrigin": true } } but for some reason I cannot make api calls to any django allauth endpoints. The proxy is working because i can make a request to /api/accounts/profile which is a custom view i created to fetch a users information. However, what I'm trying to do is use allauths pre-created endpoints such as /accounts/login or /accounts/logout. If I make a request to http://localhost:4200/accounts/login I get 404 errors that the page/view isn't found. If I remove the domain name so that the proxy kicks in - example: /accounts/login its the same thing. If I change the url to be http://localhost:8000/accounts/login I suddenly get cross origins errors, which means the url is recognized as existing but is not accessable. I have already added all of the cross origins settings to my settings.py and added crf token validation to eliminate some possibilities. Has anyone else experienced this and if so what have you done to fix it? I don't want to create views in Django, that would be … -
Razorpay integration error on python django
Unrecognized feature: 'otp-credentials'. error occured in browser console while razorpay integration and Method Not Allowed (POST): /checkout/ in terminal [TerminalBrowser Console](https://i.sstatic.net/Kn6QfxTG.png) HTML script and button already loaded above <script> var options = { "key": "rzp_test_THuJCWTGTSyCOm", // Enter the Key ID generated from the Dashboard "amount": "{{ razoramount }}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Anasulfiros", //your business name "description": "Purchase Product", "order_id": "{{ order_id }}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "handler": function(response){ console.log("success") var form = document.getElementById("myform"); // alert(form.elements["custid"].value); // alert(response.razorpay_payment_id); // alert(response.razorpay_order_id); // alert(response.razorpay_signature); window.location.href = "http://localhost:8000/paymentdone?order_id=${response.razorpay_order_id}&payment_id=${response.razorpay_payment_id}&cust_id=${form.elements["custid"].value}" }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed',function(response){ alert(response.error.description); }); document.getElementById('rzp-button1').onclick = function(e){ console.log("button click"); rzp1.open(); e.preventDefault(); } </script> {% endblock payment-gateway %} views class checkout(View): def get(self,request): user = request.user add = Customer.objects.filter(user=user) cart_items=Cart.objects.filter(user=user) famount = 0 for p in cart_items: value = p.quantity * p.product.discounted_price famount = famount + value totalamount = famount + 40 razoramount = int(totalamount * 100) client = razorpay.Client(auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) data = {"amount":razoramount,"currency":"INR","receipt":"order_rcptid_12"} client.set_app_details({"title" : "Django", "version" : "1.8.17"}) payment_response = client.order.create(data=data) print(payment_response) order_id = payment_response['id'] order_status … -
Hello, can you tell me I'm writing a website on django 4
[enter image description here](https://i.sstatic.net/OmSFrl18.jpg) Вот так у меня [enter image description here](https://i.sstatic.net/ml9pLrDs.jpg) hello, you can tell me I'm writing a site on django 4 that gives the search bar select debugger in Run and Debug with the choice of only one single action, this is Python Debugger instead of the Debug Configuration search bar with a single choice of Django. Can you tell me how to solve this problem?? That's how the person I'm using to make the launch site.Our json is completely different. I don't understand how to solve this problem -
Django password reset with front end UI
I'm working on a project that uses Django as the backend and next.js/react.js on the front end. The issue I'm running into is trying to reset the password using the UI of my front end. All of the solutions I've found involve creating the UI on the backend server with templates which I would prefer not to do. I'm able to get the following email from Django(dj_rest_auth) that provides a link with the server domain. Hello from MyApp! You're receiving this email because you or someone else has requested a password reset for your user account. It can be safely ignored if you did not request a password reset. Click the link below to reset your password. http://localhost:8000/password-reset-confirm/k/cd01t1-dfsdfdfwer2/ I've tried to override the PasswordResetSerializer like so but it doesn't work. from dj_rest_auth.serializers import PasswordResetSerializer class MyPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self) : return { 'email_template_name': 'http://localhost:3000/new-password' } And in my settings.py file I have ... REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'myapp.serializers.MyPasswordResetSerializer' } ... How can I change the link in the reset password email to one that sends the user to the client to create their new password? -
Internal Server Error by uploading django project to apache server
Try to upload my djnago project to apache2 server and at the begging hadn't an access(error 403). After somehow solved problem got new one Internal Server Error. /var/log/apache2/error.log: [Sat Sep 07 22:05:50.292291 2024] [core:warn] [pid 74852:tid 129319697659776] AH00045: child process 74853 still did not exit, sending a SIGTERM [Sat Sep 07 22:05:50.292335 2024] [core:warn] [pid 74852:tid 129319697659776] AH00045: child process 74854 still did not exit, sending a SIGTERM [Sat Sep 07 22:05:52.294434 2024] [core:error] [pid 74852:tid 129319697659776] AH00046: child process 74853 still did not exit, sending a SIGKILL [Sat Sep 07 22:05:52.294476 2024] [core:error] [pid 74852:tid 129319697659776] AH00046: child process 74854 still did not exit, sending a SIGKILL [Sat Sep 07 22:05:53.295592 2024] [mpm_event:notice] [pid 74852:tid 129319697659776] AH00491: caught SIGTERM, shutting down [Sat Sep 07 22:08:55.562107 2024] [mpm_event:notice] [pid 76122:tid 129486358599552] AH00489: Apache/2.4.52 (Ubuntu) mod_wsgi/4.9.0 Python/3.10 configured -- resuming normal operations [Sat Sep 07 22:08:55.562464 2024] [core:notice] [pid 76122:tid 129486358599552] AH00094: Command line: '/usr/sbin/apache2' /etc/apache2/sites-available/mysite.conf <VirtualHost *:80> ServerName myip WSGIScriptAlias / /my/directory/my_project/wsgi.py <Directory /my/directory/my_project> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /my/directory/my_project <Directory /my/directory/my_project> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/mysite_error.log CustomLog ${APACHE_LOG_DIR}/mysite_access.log combined </VirtualHost> If anyone needs more information, I'll be happy to provide it I've already tried … -
django-ckeditor-5 media embed config for youtube shorts
I am having django project with django-ckeditor-5 package. The default media providers of ckeditor-5 has youtube. However, I could find from the original source that the regex for youtube do not include shorts url. So, I had to add extraProviders. I tried various ways, but none of them worked. "mediaEmbed": { "previewsInData": "true", "extraProviders": [ { "name": "youtube-shorts", "url": [ r"^(https?:\/\/)?(www\.)?youtube\.com\/shorts\/([a-zA-Z0-9_-]+)$", r"/^(?:m\.)?youtube\.com\/shorts\/(.+)/", ], "html": ( '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 56.2493%;">' '<iframe src="https://www.youtube.com/embed/{matched}" ' 'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' 'frameborder="0" allow="autoplay; encrypted-media" allowfullscreen>' "</iframe>" "</div>" ), }, ], }, this is one of the method I tried, and it gives the below error. If I use like below for allowing all it works without the preview image like the screenshot below though. mediaEmbed": { "previewsInData": "true", "extraProviders": [ { "name": "all", "url": r"/^.+/", }, ], }, Anyone had experience make this work? -
Webpack Getting Variables
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Django Webpack template</title> </head> <body> <div id="root"></div> <p id="message">Template Data</p> <script id="templateDataScript" type="application/json"> {{ template_data|safe }} </script> <script src="{% static 'data.bundle.js' %}"></script> </body> </html> This seems to work file when I run it locally... However, if I Webpack this and use my bundle file online it does not recognize the Django template_data. Trying to find out is it possible to somehow incorporate my variables and data into the Webpack itself. Just searching for any insight. -
Django, how can I follow a http redirect?
I have 2 different views that seem to work on their own. But when I try to use them together with a http redirect then that fails. The context is pretty straightforward, I have a view that creates an object and another view that updates this object, both with the same form. The only thing that is a bit different is that we use multiple sites. So we check if the site that wants to update the object is the site that created it. If yes then it does a normal update of the object. If no (that's the part that does not work here) then I http redirect the update view to the create view and I pass along the object so the new site can create a new object based on those initial values. Here is the test to create a new resource (passes successfully) : @pytest.mark.resource_create @pytest.mark.django_db def test_create_new_resource_and_redirect(client): data = { "title": "a title", "subtitle": "a sub title", "status": 0, "summary": "a summary", "tags": "#tag", "content": "this is some updated content", } with login(client, groups=["example_com_staff"]): response = client.post(reverse("resources-resource-create"), data=data) resource = models.Resource.on_site.all()[0] assert resource.content == data["content"] assert response.status_code == 302 Here is the test to create … -
Prefetching complex query that does a Union
I'm trying to prefetch a related object to optimize performance. The code I'm trying to Prefetch is this; class Product(models.Model): ... def get_attribute_values(self): # ToDo: Implement this prefetch. if hasattr(self, "_prefetched_attribute_values"): return self._prefetched_attribute_values if not self.pk: return self.attribute_values.model.objects.none() attribute_values = self.attribute_values.all() if self.is_child: parent_attribute_values = self.parent.attribute_values.exclude( attribute__code__in=attribute_values.values("attribute__code") ) return attribute_values | parent_attribute_values return attribute_values What this does is the following; Get all attribute_values of itself, attribute_values is a related model ProductAttributeValue If it's a child, also get the parent attribute_values, but exclude attribute_values with attribute__codes that are already present in the child attribute_values result Do a union that combines them together. Currently, I have this prefetch; Prefetch( "attribute_values", queryset=ProductAttributeValueModel.objects.select_related( "attribute", "value_option" ) ), This works for the non child scenario, but unfortunately, there are a lot of child products and thus the performance isn't as great. So ideally, I can prefetch the combined attributes to '_prefetched_attribute_values', though I would be fine with doing two prefetches as well; For the product itself For the parent, but still needs to exclude attributes that the child itself had I have tried doing it with a Subquery & OuterRef, but no luck yet. -
How to wrap a search function in a class that inherits from wagtail Page?
Is there a way to make a search form using a wagtail template inheriting from Page? Instead of using a simple view. And how can I render it in the template? I find it more enriching to be able to use the wagtail page attributes to better style the search page, add more fields and make it translatable into multiple languages using for example wagtail localyze. class SearchPage(Page): # Database fields heading = models.CharField(default="Search", max_length=60) intro = models.CharField(default="Search Page", max_length=275) placeholder = models.CharField(default="Enter your search", max_length=100) results_text = models.CharField(default="Search results for", max_length=100) cover_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) # Editor panels configuration content_panels = Page.content_panels + [ FieldPanel('cover_image'), FieldPanel('heading'), FieldPanel('intro'), FieldPanel('placeholder'), FieldPanel('results_text'), ] def search(self, request): search_query = request.GET.get("query", None) page = request.GET.get("page", 1) active_lang = Locale.get_active() # Search if search_query: search_results = Page.objects.filter(locale_id=active_lang.id, live=True).search(search_query) # To log this query for use with the "Promoted search results" module: # query = Query.get(search_query) # query.add_hit() else: search_results = Page.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return TemplateResponse( request, "search/search_page.html", { "search_query": search_query, "search_results": search_results, }, ) My layout.html file: {% block content %} {% … -
Django IntegrityError: Foreign key constraint violation on token_blacklist_outstandingtoken
I'm encountering an IntegrityError when trying to log in to my Django application. The error suggests a foreign key constraint violation. Here are the details: Error Message django.db.utils.IntegrityError: insert or update on table "token_blacklist_outstandingtoken" violates foreign key constraint "token_blacklist_outs_user_id_83bc629a_fk_auth_user" DETAIL: Key (user_id)=(5) is not present in table "auth_user". Context This error occurs when a user attempts to log in. The POST request to /auth/login/ returns a 500 status code. Date and time of the error: [07/Sep/2024 11:08:11] Relevant Code [Include any relevant code snippets here, such as your login view or authentication configuration] Question What could be causing this foreign key constraint violation? How can I resolve this issue and allow users to log in successfully? Any insights or suggestions would be greatly appreciated. Thank you! -
Django + JS : value with double curly braces not sent to a JS function. Others are OK
A mystery hits me ! I display with a loop many shipping services available for a given order on a page containing all my orders. {% for serv in account.services %} <div class="service"> <label class="form-check-label" for="service{{order.pk}}"><small>{{serv}}</small></label> {% if forloop.first %} <input class="form-check-input" type="radio" name="service{{order.pk}}" value="{{serv.pk}}" ismulti="{{serv.is_multiparcel}}" checked> {% else %} <input class="form-check-input" type="radio" name="service{{order.pk}}" value="{{serv.pk}}" ismulti="{{serv.is_multiparcel}}"> {% endif %} {% if order.base_subtotal > serv.insurance_from %} <div class=" form-text text-danger insur-alert{{order.pk}}">Assur. appliquée car € HT sup. à {{serv.insurance_from}}</div> {% endif %} {% if order.weight > serv.max_weight %} <div class="form-text badge bg-danger" name="weight-alert">Poids commande > max. service {{serv.max_weight}} kg</div> <script> disableCheckCauseWeight("service{{ order.pk }}", "{{serv.pk}}"); </script> {% endif %} </div> {% endfor %} One of these services can be selected with a radio button and is identified by 2 prameters : service{{order.pk}} and {{serv.pk}}. Both of them are well displaying in my html code: Later in my code, for each loop, I call a JS function for disabling the given service if the order's weight is higher than the weight accepted by the service. But, {{serv.pk}} isn't sent to disableCheckCauseWeight()function, despite it's well displayed above in value="{{serv.pk}}". A console log shows well service{{order.pk}} but not {{serv.pk}}. I tried with other values like {{order.pk}}or … -
what are the steps to setup visual Studio?
How the map() function works in Python. Can someone explain with a simple example?" I was going through different topics and functions of python but then I was wondering how does map() function work, I want to understand it with simple example!! -
Populating an SQLite database from Markdown files in Django
I'm starting to learn Django and Python to migrate my website, and I'm trying to wrap my head around getting an SQLite database set up and populated. All the tutorials I see show you how to do this using the admin application and using the web UI to add posts manually, but I want Django to find the Markdown files in my folder structure and pull the info from those Markdown files and populate the database with that data. This topic (Populating a SQLite3 database from a .txt file with Python) seems to be in the direction I'm heading, but 1) it's old, and 2) it involves a CSV file. (Does this need to be in CSV? Would JSON work just as well or better, especially since I have a JSON feed on the site and will need to eventually populate a JSON file anyways?) Otherwise, I've found topics about importing files from folders to populate the database, but those tips are for Python in general, and I wasn't sure if Django had specific tools to do this kind of thing just as well or better. What's a good way to set up Django to populate an SQLite database from … -
Django REST Framework MultiPartParser parsing JSON as string
I am making a django functional based view where the request contains some JSON and a file. Using DRF's MultiPartParser is parsing the JSON section of the request as a string. what can I do to fix this? here is the view: from rest_framework.response import Response from rest_framework.request import Request from rest_framework.parsers import MultiPartParser @api_view(['POST']) @parser_classes([MultiPartParser]) def import_files(request: Request) -> Response: data = request.data print(type(data['json'])) return Response("Success", status=200) and here is the client request using python requests: import requests import json multipart_payload = [ ('json', (None, json.dumps(payload), 'application/json')), ('file', ('test.xlsx', open('test.xlsx', 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) ] put_response = requests.post(endpoint + "feature/", files=multipart_payload) print(put_response.json()) I have tried adding JSONParser to the @parser_classes decorator but it didn't work. if anyone had a similar issue any help would be great thanks -
how filter options with another select value on django admin forms
i have Address,city,state models with oneToOne relation and im trying filter citys by state when i want to add new address so the problem is i can see all citys for any state and i have no idea how to fix that. any idea? models class State(models.Model): state_name = models.CharField(max_length=50) def __str__(self) -> str: return self.state_name class City(models.Model): cityـname = models.CharField(max_length=50) state = models.ForeignKey(to=State,on_delete=models.CASCADE) def __str__(self) -> str: return self.cityـname class Adrress(models.Model): user = models.ForeignKey(to=User,on_delete=models.CASCADE) city = models.ForeignKey(to=City,on_delete=models.CASCADE) description = models.TextField() def __str__(self) -> str: return self.description admin @admin.register(State) class StateAdmin(admin.ModelAdmin): pass @admin.register(City) class CityAdmin(admin.ModelAdmin): pass @admin.register(Adrress) class AdrressAdmin(admin.ModelAdmin): pass so i expect when i want to add new address see form like this and on state change in city drop down only city for that state be visible The way I tried using custom form so i change code like this in admin and make custom widget and Jquery admin @admin.register(Adrress) class AdrressAdmin(admin.ModelAdmin): form = AdrressAdminForm forms class RelatedChoieField(forms.widgets.Select): def __init__(self, attrs=None, choices=()): super().__init__(attrs,choices) self.data = {} for obj in City.objects.all(): if not obj.state in self.data.keys(): self.data[obj.state.state_name] = [obj.cityـname] else: self.data[obj.state.state_name].append(obj.cityـname) def render(self, name, value, attrs=None, renderer=None): html = super().render(name, value, attrs) inline_code = mark_safe( f"<script>obj ={dumps(self.data,indent=4)};$(\"#id_state\").change(()=>{{$(\"#id_city\").innerHTML=\"\";for(var i=0;i<obj[$(\"#id_state\").find(\":selected\").text()].length;i++){{$(\"#id_city\").innerHTML+=$(\"<option></option>\").innerHTML=obj[$(\"#id_state\").find(\":selected\").text()][i]}} }})</script>" … -
Problems for send a file attachment using Django-Q
I'm testing Django-Q to improve my project, which involves sending study certificates. However, I'm encountering an issue. The log shows the following error: File "C:\Python311\Lib\multiprocessing\queues.py", line 244, in _feed obj = _ForkingPickler.dumps(obj) File "C:\Python311\Lib\multiprocessing\reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) TypeError: cannot pickle '_thread.RLock' object When this error appears, it starts an infinite loop that sends emails with the attached file about the certificates. I suspect that I've made a mistake somewhere, so any help would be greatly appreciated! Here is the code in my tasks.py: from django.core.mail import EmailMessage from django_q.tasks import async_task def send_email_task(subject, message, recipient_list, attachments=None): """ Sends an email asynchronously. """ email = EmailMessage(subject, message, 'victorgabrieljunior@gmail.com', recipient_list) if attachments: for attachment in attachments: email.attach(*attachment) async_task(email.send, fail_silently=False) Here my admin.py: def generate_pdf(self, request, queryset): constancia_id = queryset.values_list('id', flat=True)[0] response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="constancia.pdf"' #Code for the content in the file # Call the function from tasks.py send_email_task( "Constancia de Estudios", f'Hola {primer_nombre} {primer_apellido}, tu solicitud de constancia de estudio ha sido exitosa. ' 'Por favor revisa el archivo adjunto para obtener tu constancia de estudio', [correo], attachments=[(f'constancia_{primer_nombre}_{primer_apellido}.pdf', response.getvalue(), 'application/pdf')] ) self.message_user(request, "Constancia generada y enviada por correo exitosamente.") return response generate_pdf.short_description = "Descarga los items … -
How to apply gevent monkey patch using django-admin with huey?
I have a django app that uses huey. I want to enable the greenlet worker type for the huey consumer. Running django-admin run_huey logs this message and tasks do not run. I managed to run the huey consumer successfully with the greenlet worker type by using the manage.py and apply the monkey patching there as documented here Is it possible to achieve the same with django-admin? Do I have to create a custom manage command that applies monkey patching before the huey consumer runs? -
Django - How to use in app a profile picture after getting UID and Access_token of an user from Facebook
I successfully made a connection between my app and facebook, but I don't know how to pass ID and access_token from "User Social Auth: extra data" into User model. I tried by modifying default Django User model, by creating another model and passing user = OneToOneField, but I don't know how to pass ID and access_token. Here is my code so far: (I changed keys into "######" for security measures) Settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-&ab$_bmjpvh56kv@2#tyg*_yl&ja7f&$t!4^twuo7k1+%%k%u3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base', 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'sportowyczluchow.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', ], }, }, ] WSGI_APPLICATION = 'sportowyczluchow.wsgi.application' # Database # https://docs.djangoproject.com/en/5.1/ref/settings/#databases DATABASES = { 'default': { …