Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to auth user to Django admin site using external API end point
I'm using an external endpoint to check if the username and password are given and if it is valid I return success:true if not I return it as false. and ofc I generate a token and return it back to him. Here is the function amusing for this : @api_view(["POST"]) # decorator to make this a rest API endpoint def login_user(request): """ Login User Endpoint takes in email & password as input from the client side """ username, password = request.data["username"], request.data["password"] # authenticate function from Django auth library is used here # to check if the provided credentials are correct or not user = authenticate(username=username, password=password) # If authentication is successful then generate a token else return an error message as a JSON object if user: token, _ = Token.objects.get_or_create(user=user) the_company_object = hiring_app_company.objects.get(user=user) user_object = { "name": f"{user.first_name} {user.last_name}", "email": user.username, "image": f"https://admin.apexnile.com{the_company_object.company_logo.url}", "link":f"https://admin.apexnile.com/admin/" } return Response( {"success": True, "user": user_object, "token": token.key}, status=status.HTTP_200_OK, ) else: return Response( {"success": False, "error": "Invalid Credentials"}, status=status.HTTP_401_UNAUTHORIZED, ) The API called are being called from a totally different server which uses Next auth and it authenticates the user based on the response returned from this API call. now the problem is sometimes … -
React nginx to django gunicorn error 502 not visible on gunicorn
I'm asking this question because, despite more or less similar topics, I haven't found an answer to my problem. I have 2 servers (A and B). On server A, there is my react app using nginx to be served. On server B, there is my django drf deploying with gunicorn. Django drf is the backend of my front react app. Django is not accessible on internet but i can reach him from server A (using curl http://serverb_ip:8080). I set up react nginx conf as follow: upstream django { least_conn; server serverb_ip:8080; } server { listen 80; server_name servera_name; return 301 https://$server_name$request_uri; } server { listen 3000; listen \[::\]:3000; server_name pro.boutigou.fr; access_log /var/log/nginx/app.log; root /home/bouti/frontend/producer/build; client_max_body_size 10M; location /producer/api/v1/ { access_log /var/log/nginx/app_proxy.log; error_log /var/log/nginx/error_proxy.log debug; proxy_pass http://django; } location / { access_log /var/log/nginx/app_http.log; try_files $uri /index.html; add_header X-Frame-Options SAMEORIGIN; } } And my gunicorn set up on serverb: \[Unit\] Description=gunicorn daemon Requires=gunicorn.socket After=network.target \[Service\] User=bouti Group=www-data WorkingDirectory=/home/bouti/backend/api ExecStart=/home/bouti/backend/env/bin/gunicorn \\ --access-logfile - \\ --workers 3 \\ --bind unix:/run/gunicorn.sock \\ api.wsgi:application \[Install\] WantedBy=multi-user.target Request from react to my backend are visible in /var/log/nginx/app_proxy.log and /var/log/nginx/error_proxy.log. But there are not visible in gunicorn journal. In /var/log/nginx/error_proxy.log, there is: 2023/10/22 14:30:41 \[debug\] 76218#76218: \*13234 http … -
CORS issue between Django backend and React frontend in Docker environment
I have a Django backend and a React frontend set up in separate Docker containers, both running on the same Docker network. The backend is accessible via the DNS backendServer and the frontend via frontendServer. I'm encountering a CORS issue when trying to make API requests from my React frontend to my Django backend. The error message in the browser console is: Access to XMLHttpRequest at 'http://localhost:8000/api/project/?page=1' from origin 'http://192.168.1.63:3000' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`. Is there something else I might be missing or another configuration I need to make to allow requests from my React frontend to my Django backend? Any help or suggestions would be greatly appreciated. Thank you! I've tried the following steps to resolve the issue: Installed and configured the django-cors-headers middleware in my Django project. Added 'corsheaders' to INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' to MIDDLEWARE in my settings.py file. Set CORS_ALLOWED_ORIGINS to include my frontend URL (http://192.168.1.63:3000). Ensured that my Docker containers are on the same network. Despite these steps, I'm still encountering the CORS issue. The 192.168.1.63 is my dev server that hosts the docker services. -
JSON from api request in func app encoded differently to that of a Django app
I have a Django application which contains a function that calls an API and adds the data from the response into my database. I am trying to move this function into an Azure function app, however the JSON that is returned from the request seems to be encoded differently which is causing the database insert to fail. Request function from Django: def fetch_magic_set_data(code, max_retries=3, sleep_base=2): for retry in range(max_retries): try: response = requests.get(f'https://mtgjson.com/api/v5/{code}.json') response.raise_for_status() magic_sets_json = response.json() if 'data' in magic_sets_json and 'cards' in magic_sets_json['data']: return True, magic_sets_json['data'] else: print(f'Response is empty for {code}, retrying...') except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except RequestException as req_err: print(f'Request error occurred: {req_err}') sleep_time = sleep_base * (2 ** retry) time.sleep(sleep_time) return False, None Request function from function app: def get_response(url, max_attempts=10): for attempt in range(max_attempts): try: response = requests.get(url) if response.status_code == 200: return response elif 400 <= response.status_code < 600: logger.warning(f"Status: {response.status_code}. Error from {url}.") if response.status_code == 404: return None except requests.RequestException as e: logger.warning(f"Attempt {attempt + 1} of {max_attempts}. Error: {e}") if attempt < max_attempts - 1: time.sleep((2 ** attempt) + (attempt % 2)) else: logger.error(f"Failed to get response from {url} after {max_attempts} attempts.") return None return None … -
Add Log entry on Model Export Actions
I have enabled Log entries in the Django Admin class CustomLogEntryAdmin(admin.ModelAdmin): list_display = [ "action_time", "user", "content_type", "object_id", "object_repr", "action_flag", "change_message", ] # list filter list_filter = ["action_time", "user", "content_type"] # search search_fields = ["user__username", "object_repr"] admin.site.register(LogEntry, CustomLogEntryAdmin) And I have another model whose admin.py code is like this class RegAdmin(ExportActionMixin, admin.ModelAdmin): resource_class = RegAdminResource def has_view_permission(self, request, obj=None): return True def has_module_permission(self, request): return True By default all change, addition and deletion entries are logged but I also want to log an entry when any export action is performed on it. ChatGPT suggests that I should something like this # in admin class def export_action(self, request, *args, **kwargs): # Log the export action LogEntry.objects.create( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(self.model).id, object_id=None, object_repr=str(self.model), action_flag=1, # Assuming 1 stands for the action flag of 'change' change_message="Export action triggered.", ) return super().export_action(request, *args, **kwargs) But this function is not triggered when an export action is performed. I confirmed by adding a print statement. How should I do this? Any help would be appreciated. -
Is there a way to pass Javascript variable to Django template before form submit?
I am trying to get a selected approver and do a validation check before a form gets submitted in Django...It's turning out to be fairly complicated...I've gotten most of the way there...but can't seem to figure out how to "get" the ID translated in the Django template...I've gotten the ID...but can't seem to make the final connection.... Here's my AJAX... $("#avail").on("click", function(event) { var modalavail = document.getElementById("myModalavail"); var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); event.preventDefault(); $(window).unbind('beforeunload'); $.ajax({ method: 'get', headers: { "X-CSRFToken": token }, url: "", processData: false, contentType: false, cache: false, enctype: 'multipart/form-data', success: function(resp) { modalavail.style.display = "block"; for (var checkbox of markedCheckbox) { console.log(checkbox.value + ' '); } }, error: function (request, status, error) { console.log(request.responseText); showAjaxFormErrors(JSON.parse(request.responseText)); $('html, body').animate({ scrollTop: 0 }, 50); }, }); }); Here's my HTML... Check Availability <div class="table56"> {% for entry in form.approvers %} <table class="table57"> <thead> <tr> <th class="title156">Name</th> <th class="title118">Available?</th> </tr> </thead> <tbody> <tr> <td class="title156">{{ entry.name }}</td> {% if not start_conflict or end_conflict or during conflict %} <td class="title117">Yes</td> {% else %} <td class="title117">No</td> {% endif %} </tr> </tbody> </table> {% endfor %} </div> <input type="hidden" id="modal-approvers"> <button type="button" class="button210" id="modalcloseavail">Close</button> </div> Here's my form... class DailyPlannerForm(forms.ModelForm): class Meta: model = NewDailyPlannerEvent … -
How to add Google AdSense to my Django blog project?
I have a Django blog app. The Google Adsense said that the script is not found in my website, however I copied it. Thank you in advance. I have a default.html which is extended to all the other html pages. It contains the header with login/logout and signup buttons, the logo, a welcoming message and most importantly the Google Ads scripts. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" property="og:description" content="These articles are about movies and created by users."> <meta name="keywords" content="seo, python, django, movies, articles, opinions, posts, users, actress, actor, hollywood, mainstream, film"> <meta name="author" content="************"> <!-- Google AdSense meta tag --> <meta name="google-adsense-account" content="ca-pub-************"> <title>Articles</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="************" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles.css' %}"> <link rel="icon" type="image/x-icon" href="{% static 'favicon.ico' %}"> <!-- Google AdSense --> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-************" crossorigin="anonymous"></script> <!-- Google tag (gtag.js) --> <script async src="https://www.googletagmanager.com/gtag/js?id=************"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '************'); </script> <!-- Google Acceptable-Ads Message --> <script async src="https://fundingchoicesmessages.google.com/i/pub-************?ers=1" nonce="************"></script><script nonce="************">(function() {function signalGooglefcPresent() {if (!window.frames['googlefcPresent']) {if (document.body) {const iframe = document.createElement('iframe'); iframe.style = 'width: 0; height: 0; border: none; z-index: -1000; left: -1000px; top: -1000px;'; iframe.style.display = … -
Why is this block not overwriting the image?
I have : <a class="navbar-brand" href="/" >{% block brand %}<img src="{% static 'logo.png' %} " />{% endblock%}</a > How ever the block is still showing the same image of the child template, how can I overwrite it? just for the "/" page. I have a static folder in the main project folder and a template folder, I have added their respective config in settings.py see: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], STATICFILES_DIRS = [BASE_DIR / 'static'] here is the child template: {% extends "base.html" %} {%load static%} {% block brand %}<img src="{% static 'reviews/logo.png' %}" />{%endblock%} -
Streaming data using Langchain RetrivalQA
I am using Django, and Langchain with OpenAI to generate responses to my prompts. I was trying to enable streaming using Server-Sent-Events (SSE) in my API function. When I run my code It does stream the OpenAI output in the terminal, but it returns the output as a whole to the client once the streaming has ended. I tried using StreamingHttpResponse but, didn't get any success. It would be really awesome if any one can suggest what's wrong in the code. API Function: @api_view(['GET','POST']) def sse_view(request): if request.method != 'POST': return Response({"message": "Use the POST method for the response"}) url = request.data.get("url") questions = request.data.get("questions") prompt = request.data.get("promptName") if not url or not questions: return Response({"message": "Please provide valid URL and questions"}) # Process the documents received from the user try: doc_store = process_url(url) if not doc_store: return Response({"message": "PDF document not loaded"}) except Exception as e: return Response({"message": "Error loading PDF document"}) custom_prompt_template = set_custom_prompt(url,prompt) # Load and process documents loader = DirectoryLoader(DATA_PATH, glob='*.pdf', loader_cls=PyPDFLoader) documents = loader.load() text_splitter = CustomRecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=30) texts = text_splitter.split_documents(documents) #Creating Embeddings using OpenAI embeddings = OpenAIEmbeddings(chunk_size= 16, openai_api_key= openai_gpt_key,) db = FAISS.from_documents(texts, embeddings) db.save_local(DB_FAISS_PATH) search_kwargs = { 'k': 30, 'fetch_k':100, 'maximal_marginal_relevance': True, 'distance_metric': … -
I have two form to get email in my webpage but whenever i submit the form the message form is not valid is displayef
urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('home', views.home, name='home'), path('about', views.about, name='about'), path('contact', views.contact, name='contact'), path('email-submit/form1/', views.email_submit, name='email-submit1'), path('email-submit/form2/', views.email_submit, name='email-submit2'), ] forms.py from django import forms from .models import EmailSubscription class EmailSubscriptionForm(forms.ModelForm): class Meta: model = EmailSubscription fields = ['email'] models.py from django.db import models class EmailSubscription(models.Model): email = models.EmailField(unique=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib import messages from .forms import EmailSubscriptionForm def home(request): return render(request, 'maincontent/home.html') def about(request): form1 = EmailSubscriptionForm() form2 = EmailSubscriptionForm() return render(request, 'maincontent/about.html', {'form1': form1, 'form2': form2}) def contact(request): return render(request, 'maincontent/contact.html') def email_submit(request): if request.method == 'POST': form_id = request.POST.get('form_id') if form_id == 'form1': form = EmailSubscriptionForm(request.POST) elif form_id == 'form2': form = EmailSubscriptionForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] form.save() messages.success(request, f'Thank you for subscribing with email: {email} ({form_id.capitalize()})') else: messages.error(request, f'Form {form_id.capitalize()} is not valid.') form1 = EmailSubscriptionForm() form2 = EmailSubscriptionForm() return render(request, 'maincontent/about.html', {'form1': form1, 'form2': form2}) email_form_1.html <form class="email-submit" id="data-form-1" method="post" action="{% url 'email-submit1' %}"> {% csrf_token %} <input type="hidden" name="form_id" value="form1"> <input type="email" placeholder="Enter your email..." name="{{ form.email_address.name }}" id="{{ form.email_address.id }}" required/> <button type="submit"> Sign … -
How Post Amount Number From React to Django py script
hello i want send data from my react app.jsx to django script file that scirpt have amount variable and need number to give to him in my script from django.db import models from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from . serializer import * from azbankgateways import (bankfactories,models as bank_models,default_settings as settings,) import logging from django.urls import reverse from django.shortcuts import render from django.http import HttpResponse, Http404 from django.http import JsonResponse # Bank from azbankgateways.exceptions import AZBankGatewaysException from azbankgateways.models.banks import Bank # API # Create your models here. # ViewSets define the view behavior. class BankViewSet(viewsets.ModelViewSet): queryset = Bank.objects.all() serializer_class = BankSerializer # Bank Functions def go_to_gateway_view(request): # خواندن مبلغ از هر جایی که مد نظر است amount = 5000 # تنظیم شماره موبایل کاربر از هر جایی که مد نظر است user_mobile_number = '+989112221234' # اختیاری factory = bankfactories.BankFactory() try: bank = factory.auto_create() # or factory.create(bank_models.BankType.BMI) or set identifier bank.set_request(request) bank.set_amount(amount) # یو آر ال بازگشت به نرم افزار برای ادامه فرآیند bank.set_client_callback_url('/callback-gateway') bank.set_mobile_number(user_mobile_number) # اختیاری # در صورت تمایل اتصال این رکورد به رکورد فاکتور یا هر چیزی که بعدا بتوانید ارتباط بین محصول یا خدمات را با این # پرداخت برقرار کنید. bank_record = … -
CSRF verification error from dockerized Django behind dockerized nginx
I have two docker containers running together, one for a Django app using gunicorn, and one for nginx serving static files and redirecting requests to the Django app. I have used different ports for the Django/gunicorn server, exposed only to nginx (8000), the nginx server, exposed in the docker container (80), and externally when using the docker container (so I mapped the port to a different one, say 8888). I also access it with a "xyz.local" host name from the device where docker runs. This is all happening in a home network, no HTTPS involved. Now when I submit a form, e.g. the admin interface's login form, I get a CSRF verification failure saying xyz.local:8888 is not a trusted origin. I understand that I can add "http://xyz.local:8888" to the CSRF_TRUSTED_ORIGINS to make it work, or disable CSRF protection altogether, but I'm wondering if that is the correct/best way in this setup. I would like to have the Django docker container be as unaware of the outside world as possible, so that I can just run it on another device having a different host name or with a different docker-compose configuration using a different port, without having to rebuild the docker … -
Django Unit Test for class with TokenAuthentication
this is my first time writing unit test so in my Django Project I have this class from views.py class AllClientProfilesView(generics.ListAPIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = ClientProfileSerializer def get_queryset(self): return ClientProfile.objects.all() and my test code is class AllClientProfilesViewTest(APITestCase): def setUp(self): call_command('flush', interactive=False) self.user = User.objects.create_user(id='2' , phone_number=506879765) self.token = Token.objects.create(user=self.user) self.profile1 = ClientProfile.objects.create(name='Profile 1', ) self.profile2 = ClientProfile.objects.create(name='Profile 2', ) self.profile3 = ClientProfile.objects.create(name='Profile 3', ) def test_view_requires_authentication(self): url = reverse('myURL') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_get_all_client_profiles(self): url = reverse('myURL') self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.token.key}') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) expected_profiles = ClientProfile.objects.all() self.assertEqual(len(response.data), expected_profiles.count()) for data, expected_profile in zip(response.data, expected_profiles): serializer = ClientProfileSerializer(expected_profile) self.assertEqual(data, serializer.data) but when I run it I got this error and I don't know how to fix it return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id -
{'sales@mydomain.co': (553, b'5.7.1 <abc@gmail.com>: Sender address rejected: not owned by user sales@mydomain.co')}
I have a contact form on my website where users fill in their name, email and message to contact support which in this case is sales@mydomain.co and say the sender's email is abc@gmail.com. When a user submits the form, the form yields an error {'sales@mydomain.co': (553, b'5.7.1 <abc@gmail.com>: Sender address rejected: not owned by user sales@mydomain.co')} The form works if the sender's email belongs to the organization sales@mydomain.co. Is it possible to for a user to send an email(using a different organization email, such as Gmail) through the online form? here is my forms.py class ContactForm(forms.Form): name = forms.CharField(label='Your name', max_length=100) email = forms.EmailField(label='Your email', max_length=100) message = forms.CharField(max_length=600, widget=forms.Textarea) def send_mail(self): logger.info("Sending email to customer service") subject = "Site message" message = f"From: {self.cleaned_data['name']} <{self.cleaned_data['email']}>\n{self.cleaned_data['message']}" sender_email = self.cleaned_data['email'] # Use the user's email as the sender recipient_list = ['sales@mydomain.co'] # My domain email address send_mail( subject, message, sender_email, recipient_list, fail_silently=False, ) -
Attempting to migrate an Django ImageField, but failing to migrate
I am currently facing a problem with trying to migrate a Django Image field from a folder named media_root located inside a folder named static_cdn inside of my current project here is what my current file structure looks like as that may help; veganetworkmain -----profiles -------static_cdn ---------media_root ----------test.png Test.png is a png file that is generated using a picture generation algorithm using Pillow, here is what Test.png actually looks like: However what actually happens when I try to implement the code to get the picture into my program using a Django Image Field is that it just becomes white as seen here: I had tried methods like using python manage.py makemigrations, python manage.py migrate, changing the static by changing url_patterns and setting and even python ./manage.py makemigrations profiles. Here are the links to each method that I had tried: Django - makemigrations - No changes detected Page not found 404 Django media files And finally here is my code that I am currently working with during this time: models.py from django.db import models from django.shortcuts import reverse from django.contrib.auth.models import User from .utils import get_random_word from django.template.defaultfilters import slugify from django.db.models import Q -------------------------------------------------- class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) … -
400 Bad Request Error in an application using Django, Gunicorn, and Nginx
I've been trying to troubleshoot my issue with no success for a while now, so I hope posting here helps. I am developing an application using Django REST Framework, Gunicorn, and Nginx. The idea is to have Gunicorn serve the Django applicaiton, and have Nginx be used as a reverse proxy that holds the SSL certs. I've referenced multiple guides on hosting applications using these three technologies, with little success. I have my Django application connected to gunicorn using a sock file on port 80, and my Nginx server blocks listen for both port 80 and 433 (for SSL purposes). I have tried just about everything I can think of, and yet I am still getting a 400 - Bad Request error whenever I navigate to the domain that should serve the API. This is my Nginx sites-available file, with just a couple of names changed for security purposes: server { listen 80; server_name www.querymarketplace.net; return 301 http://querymarketplaceapi.net$request_uri; } server { listen 80; server_name querymarketplaceapi.net 157.245.10.103; location /static/ { root /home/jbisc/qm_marketplace/; } location / { include proxy_params; proxy_pass http://unix:/home/jbisc/qm_marketplace.sock; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; } } server { listen 443 ssl; listen [::]:443 ssl; # Optional: … -
How do I pass a Javascript variable to my Django framework to be used in template or via get_context?
I have been working to pass form values to a modal using Django. I have gotten most of the way there, but I can't quite make out how to connect the two.... Here is my AJAX... $("#avail").on("click", function(event) { var modalavail = document.getElementById("myModalavail"); var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); event.preventDefault(); $(window).unbind('beforeunload'); $.ajax({ method: 'get', headers: { "X-CSRFToken": token }, url: "", processData: false, contentType: false, cache: false, enctype: 'multipart/form-data', success: function(resp) { modalavail.style.display = "block"; for (var checkbox of markedCheckbox) { console.log(checkbox.value + ' '); } }, error: function (request, status, error) { console.log(request.responseText); showAjaxFormErrors(JSON.parse(request.responseText)); $('html, body').animate({ scrollTop: 0 }, 50); }, }); }); Here is my HTML... <button class="button209" id="avail">Check Availability</button> <div id="myModalavail" class="modal"> <div class="modal-content"> <span class="close"></span> <img class="logo4" src="/static/images/threecircles.svg"> <div class="table56"> {% for entry in form.approvers %} <table class="table57"> <thead> <tr> <th class="title156">Name</th> <th class="title118">Available?</th> </tr> </thead> <tbody> <tr> <td class="title156">{{ entry.name }}</td> <td class="title117">Yes</td> </tr> </tbody> </table> {% endfor %} </div> <input type="hidden" id="modal-approvers"> <button type="button" class="button210" id="modalcloseavail">Close</button> </div> </div> Obviously, form.approvers is going to give me all of the eligible approvers in my form....However I'm just trying to pass the selected approvers... This line of code is working flawlessly.... var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked'); It is getting the … -
A function working in a custom file but not in a "custom migration" on Django
I am beginner in Django and just started learning migrations. In a DB table, I am trying to remove a row that has a specific field value. When I create a custom file which uses Django settings, the function properly deletes the row. But when I use the snippet in another function in a custom migration file, the deletion doesn't take place. It is possible that I am missing something elementary as a beginner. So I am trying to delete all orders the status of which is cancelled. The function that works in a separate file is: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm_skeleton.settings") django.setup() from main_app.models import Order def delete_test_fnc(): all_orders = Order.objects.all() for i in range(len(all_orders) - 1, -1, -1): order = all_orders[i] if order.status == "Cancelled": order.delete() delete_test_fnc() The custom migration where delete doesnt work (other two modifications work without issues) is: from datetime import timedelta from django.db import migrations CURRENT_ORDERS = [] def modify_delivery_warranty(apps, schema_editor): global CURRENT_ORDERS orders = apps.get_model("main_app", "Order") all_orders = orders.objects.all() CURRENT_ORDERS = all_orders for i in range(len(all_orders) - 1, -1, -1): order = all_orders[i] if order.status == "Cancelled": order.delete() elif order.status == "Pending": order.delivery = order.order_date + timedelta(days=3) elif order.status == "Completed": order.warranty = "24 months" order.save() … -
anyone face this issue in django?
enter image description here when i created a employee form and view the form it show like as image. <tr> <td>{{ form.employee_name.label }}</td> <td>{{ record.employee_name }}</td> </tr> <tr> <td>{{ form.dob.label }}</td> <td>{{ record.dob }}</td> </tr> <tr> <td>{{ form.age.label }}</td> <td>{{ form.age }}</td> </tr> only age field show like this, i review all my code , it didnt find and issue, if face same issue please help me -
How to clear validation error in django when the value is in timezone and it must be an decimal value?
I am a beginner in django and in fact,now only i started my learning process about django Now i faced an error in my program I created an app and assigned some textfields in it After that i do some modulations and at a particular time,it asks for an argument to be given in my function to run properly and it shows some examples of how the argument be like And i mistakenly give the timezone.now() for a decimalvalue function Now it shows error like "current date time"value must be a decimal number and i am frustrated upon this error So can someone help me to clear this so that i can continue my journey seemlessly I tried to run a program app called products and i give a decimalvalue() in it with a missing argument and it shows an argument must ve given and asks Would you gonna give now? With for an example "timezone.now" And i give the same example as my argument and i get an error which is "current date time" value must be a decimal number And i want to clear the timezone.now function and wanna put some value or something to run the programthis … -
How to hide password field from request.user in django?
i am learning django currently and i have a question about request.user. I have made an custom user model and i use django's built in authentication. When i use login function, everything works right. When i print request.user it returns the current user. When i print request.user.password it returns the user's hashed password. I know that it is not safe to expose user's password in any form. So my question is how can i exclude password field form request.user I have tried to write a serializer but with no success. User's model from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser, BaseUserManager from post.models import Post class UserManager(BaseUserManager): def create_user(self, email, username, fullName, password): if not email: raise ValueError("User must provide Email") if not username: raise ValueError("User must provide username") if not fullName: raise ValueError("User must provide full name") user = self.model( email=self.normalize_email(email), fullName=fullName, username=username ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, full_name, password=None): """Create user and give Superuser privilages""" user = self.create_user( email=email, full_name=full_name, username=username, password=password ) user.is_active = True user.is_staff = True user.is_superuser = True print("Superuser privilages activated.") user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField("Email", unique=True) username = models.TextField("Username", max_length=100, unique=True) fullName … -
Running DRF endpoints in a venv with gunicorn
I have some APIs implemented with DRF and I want those to run in a venv. I am using gunicorn. I run gunicorn like this: /path_to_venv/bin/gunicorn But in the API code I log os.getenv('VIRTUAL_ENV') and it's None. Is that valid evidence that the code is not running in the venv? If so, how can I force it to run in the venv? If not, how can I validate that it is running in the venv? -
Extract Musical Notes from Audio to array with FFT
I'm trying to create a project in which I upload an audio file (not necessarily wav) and use FFT endpoint to return an array with the names of the sounds. Currently, I have such code, but even though I upload a file with only the sound A, it receives the value E-10, and when uploading, for example, title, I receive only one sound. Would anyone be able to help me? import os from django.shortcuts import render from django.http import JsonResponse from pydub import AudioSegment import numpy as np from noteQuiz import settings #Names of the notes NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] def freq_to_number(f): return 69 + 12*np.log2(f/440.0) def number_to_freq(n): return 440 * 2.0**((n-69)/12.0) def note_name(n): return NOTE_NAMES[n % 12] + str(int(n/12 - 1)) def find_top_notes(fft, xf): if np.max(fft.real) < 0.001: return [] lst = [x for x in enumerate(fft.real)] lst = sorted(lst, key=lambda x: x[1], reverse=True) idx = 0 found = [] found_note = set() while (idx < len(lst)) and (len(found) < 1): f = xf[lst[idx][0]] n = freq_to_number(f) n0 = int(round(n)) name = note_name(n0) if name not in found_note: found_note.add(name) s = [note_name(n0)] found.append(s) idx += 1 return found def … -
Django broken pipe error when handling large file
A server developed using the Django framework is hosted in a local environment, and a broken pipe error occurs in the process of processing large files. The current problem is the code below, which is to respond by changing the DICOM file to the png extension through a separate view to deal with the DICOM file. There is no problem in normal cases, but a broken pipe error occurs when processing about 15MB of files. # javascript code for request file data in html template function loadImages(images, fileType, index) { event.preventDefault(); if (index < images.length) { var image = images[index]; var fileName = image.image_url.split('/').pop(); var imageData = { fileName: fileName, }; imageInfoArray.push(imageData); var img = new Image(); img.onload = function() { var filePreviewHTML = ` <li class="add-image-${index}"> <a href="javascript:void(0)" class="img-wrap" data-id="${index}"> <img src="${(fileName.endsWith('.DCM')) ? '/dicom/' + fileName : image.image_url}" alt="ask-file-img"/> <button class="remove-file" onclick="disableImage('${image.image_url}')"><i class="material-icons">close</i></button> </a> <p class="file-name">${fileName}</p> </li> `; var filePreview = $('.file-preview[data-file="' + fileType + '"]'); filePreview.append(filePreviewHTML); loadImages(images, fileType, index + 1); } img.src = (fileName.endsWith('.DCM')) ? '/dicom/' + fileName : image.image_url; } // view code for handling DICOM file def show_dicom(request, file_path): file_path = os.path.join(settings.MEDIA_ROOT, "xray_images", file_path) dicom = pydicom.dcmread(file_path) image_array = apply_voi_lut(dicom.pixel_array, dicom) image_array_2d = image_array[0] if … -
Flutter Web: Assets Not Loading Correctly from main.dart.js Using Current Relative URL Instead of Base HREF
I'm currently working on hosting a Flutter web application using a Django web server on an Ubuntu 20.2 environment. The Flutter version I'm using is 3.13.5, channel stable, and my project structure has the Flutter web project located in the static folder. I've been facing an issue where the Flutter web application cannot locate the FontManifest.json file. It seems like this file is being sought using the current URL (relative) instead of the base URL defined in the index.html file. Assets loaded from index.html work correctly with the base href directed to static directory, but those loaded from main.dart.js and are using the current URL. Has anyone encountered a similar issue or has insights on how to ensure that all assets, including FontManifest.json, loaded from main.dart.js use the base URL as intended? I am almost inclined to reference the missing visual assets in main.dart through the Network module but I think Flutter should have a configuration option to determine the static-uri-location where the app will be hosted with all it's static files instead of just having to rely on the relative-uri for static files. 1.I tried fetching those 2 files (AssetManifest.bin + FontManifest.json) through the main.dart.js but that does not …