Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None)
I am new to web development and trying to create a language translation app in Django that translates uploaded documents. It relies on a series of interconversions between pdf and docx. When my code ouputs the downloaded translated document I sometimes get a com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None). Here is the full error message: Exception Location: C:\Users\John\tutorial-env\Lib\site-packages\win32com\client\dynamic.py, line 86, in _GetGoodDispatch Raised during: translator_upload.views.translateFile Python Executable: C:\Users\John\tutorial-env\Scripts\python.exe Python Version: 3.11.4 Python Path: ['C:\\djangoProjects\\mysite', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\John\\tutorial-env', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32\\lib', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\Pythonwin'] Here is my code: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranslatedDocument from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage import docx from pdf2docx import parse from docx2pdf import convert import time #remove # Create your views here. @csrf_protect def translateFile(request) : file = '' if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path)) response = HttpResponse(file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response else: form = UploadFileForm() return render(request, 'translator_upload/upload.html', {'form': form}) def reConverter(inputDocxPath): return convert(inputDocxPath) def translateDocx(aDocx, … -
How can we call middleware before urls.py
Middleware `class NetworkCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): domain = request.get_host() if not self.is_valid_domain(domain): return HttpResponseForbidden("Invalid Network") response = self.get_response(request) return response def is_valid_domain(self, domain): networkDomainModel = NetworkDomainModel.loadNetworkByDomain(domain) if networkDomainModel is None: return False obj = NetworkComponent() obj.setupNetwork(networkDomainModel.network_id) return True` NetworkComponent Class contain getId() methods urls.py `if NetworkComponent().getId() is not None: print(NetworkComponent().getId())` Getting None value while running the server Please help me out -
htmx:targetError with {% block content %}
im using htmx with Django. I have the problem, as soon as i add my `{% extends base.html' %} {% load static %} {% block content %} {% endblock content %}` the hx-target leads to a htmx:targetError. This works (search_results.html): <h1>Search Results</h1> {% if results %} <ul> {% for supplier in results %} <li> <strong>Supplier Number:</strong> {{ supplier.supplier_number }}<br> <strong>Name:</strong> {{ supplier.name }}<br> <strong>Street:</strong> {{ supplier.street }}<br> <!-- Weitere Felder hier einfügen --> <a href="{% url 'supplychainmanagement:add_order' %}?supplier_name={{ supplier.name }}" class="select-supplier" hx-get="{% url 'supplychainmanagement:add_order' %}?supplier_name={{ supplier.name }}" hx-target="#bestellungen-list" hx-boost>Lieferant auswählen</a> </li> {% endfor %} </ul> {% else %} <p>No results found.</p> {% endif %} ** this doesnt** (search_results.html): {% extends 'base.html' %} {% load static %} {% block content %} <h1>Search Results</h1> {% if results %} <ul> {% for supplier in results %} <li> <strong>Supplier Number:</strong> {{ supplier.supplier_number }}<br> <strong>Name:</strong> {{ supplier.name }}<br> <strong>Street:</strong> {{ supplier.street }}<br> <!-- Weitere Felder hier einfügen --> <a href="{% url 'supplychainmanagement:add_order' %}?supplier_name={{ supplier.name }}" class="select-supplier" hx-get="{% url 'supplychainmanagement:add_order' %}?supplier_name={{ supplier.name }}" hx-target="#bestellungen-list" hx-boost>Lieferant auswählen</a> </li> {% endfor %} </ul> {% else %} <p>No results found.</p> {% endif %} {% endblock content %} this is my base.html: <!DOCTYPE html> <html lang="en"> {% load static %} … -
Check duplicate data in database using Django
I have a problem which I want to check if data is duplicate based on name and date_travel, let say I add an item name Lebron James and choose multiple date flatpickr like 24-08-2023, 25-08-2023 and the expected result should return a JsonResponse says Duplicate date travel since In the image below the date 24-08-2023 already exist under the name of Lebron james but my problem it always return to else statement evein it has duplicate travel, hope someone helps me thanks in advance Here's what I've Tried I've plan to split and used loop in every date and return in if existed/duplicate in database but it won't work @csrf_exempt def item_add(request): employeename = request.POST.get('EmployeeName') travel_date = request.POST.get('DateTravel') # Split the date string into individual dates individual_dates = travel_date.split(',') for date in individual_dates: cleaned_date = date.strip() query = """ SELECT date_travel FROM tev_incoming WHERE name = %s AND date_travel LIKE %s; """ with connection.cursor() as cursor: cursor.execute(query, [employeename, cleaned_date]) results = cursor.fetchall() if results: return JsonResponse({'data': 'error', 'Duplcate date travel':results}) else: return JsonResponse({'data': 'success', 'message': "Unique travel and name"}) Html input <input type="text" class="form-control" name="DateTravel" placeholder="DD-MM-YYYY" id="dateField"/> script $('#dateField').flatpickr({ mode: 'multiple', allowInput: true, dateFormat: 'd-m-Y', locale: { firstDayOfWeek': 1 // … -
Django Autocomplete Light Select2 generates multiple selectboxes for declarative field
I was expecting to see a single functioning widget, but instead have two partially functioning ones. I have a Work and a Parent Work; each Work can have 0 or 1 ParentWork. models.py class ParentWork(UUIDModel): url_name = "parent_work_detail" class Work(models.Model): parent_work = models.ForeignKey(ParentWork, models.SET_NULL, null=True, blank=True) ... other fields I am using DAL for forms: forms.py class ParentWorkForm(forms.ModelForm): related_works = forms.ModelMultipleChoiceField( label="Related Works", queryset=Work.objects.all().order_by("title"), required=False, widget=autocomplete.ModelSelect2Multiple(url="autocomplete_work"), ) class Meta: model = ParentWork exclude = [] required = ["name"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # for the Parent Works update form, set the initial value of the related_works field try: instance = kwargs.get("instance") if instance: self.fields["related_works"].initial = instance.work_set.all() except Exception as e: print(e) I have to declare related_works on the ModelForm as it is stored on the Work, not ParentWork. Relevant snippet from parent_work_form.html template: {% block content %} <div class="admin-container"> <form method="post" action="." class="mt-4" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="mt-10 w-full flex justify-between"> {% if object %} <a href="{% url "parent_works_delete" object.uuid %}" class="text-gray-400 my-auto">Delete</a> {% else %} <span></span> {% endif %} <span> <a href="{% url "parent_works_list" %}" class="cancel">Cancel</a> <button>Save</button> </span> </div> </div> </form> {% endblock %} {% block extra_scripts %} <!-- parent form --> {% … -
Error with downloading "pip install uwsgi" for django project
I have a django project, where I needed to download uwsgi for production use. When trying to download the package, I get the following error (venv) C:\Users\basti\OneDrive - Sofiehøj Ejendomsadministration\OneDrive\PrimusWeb\Main\primusweb-new\portfolio>pip install u wsgi Collecting uwsgi Using cached uwsgi-2.0.22.tar.gz (809 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [8 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\basti\AppData\Local\Temp\pip-install-ds7pxw97\uwsgi_ebb78347cc174fc080e8b57246882331\setup.py", line 3, in <module> import uwsgiconfig as uc File "C:\Users\basti\AppData\Local\Temp\pip-install-ds7pxw97\uwsgi_ebb78347cc174fc080e8b57246882331\uwsgiconfig.py", line 8, in <module> uwsgi_os = os.uname()[0] AttributeError: module 'os' has no attribute 'uname'. Did you mean: 'name'? [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. (venv) C:\Users\basti\OneDrive - Sofiehøj Ejendomsadministration\OneDrive\PrimusWeb\Main\primusweb-new\portfolio> I have tried to search for similar problems, but I can't find any. I have also asked chatGPT for any help, but it doesn't lead anywhere. I know it has something to do with the … -
Django models sorting by address
I need to create a model for an Event. The event must have an address so that in the future I can sort the models by address (by city). How to do it? How to sort models by city if the address is written in one line? Or would it be better to make a separate field for the city? class TeamEvent(models.Model): title = models.CharField(max_length=255) logo = models.ImageField(blank=True, null=True) description = models.TextField(null=True, blank=True) date = models.DateTimeField() address = models.CharField(max_length=500, null=True, blank=True) teams = models.ManyToManyField(Team, blank=True, null=True) cat = models.ForeignKey(Category, on_delete=models.DO_NOTHING) def __str__(self): return self.title def get_absolute_url(self): return reverse('TeamEventDetail', kwargs={'pk': self.pk}) -
Trying to fill a form returns Cannot query "useraccount": Must be "SellerAccount" instance
I am trying to build a trading market sort of app, and I have models that have foreign keys connected in a multiple level sort of hierarchy. They are as follows: models.py class SellerAccount(models.Model): # unimportant fields user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.user.username class SellerCardDetail(models.Model): # unimportant fields seller_details = models.ForeignKey(SellerAccount, on_delete=models.CASCADE) def __str__(self): return self.seller_details.user.username The forms in question are simply formsets with only the required fields added as an argument. views.py @login_required(login_url="/account/") def add_seller_card(request): card_form = SellerCardFormSet # imported from forms.py user = SellerAccount.objects.get(user=request.user) # imported from models.py if request.method == "POST": formset = card_form(request.POST, request.FILES, instance=user) if formset.is_valid(): formset.save() messages.success(request, "Successfully listed a card!") return redirect("/") else: formset = card_form(instance=request.user) return render(request, 'account/profile/addcard.html', {"add_card": formset}) else: print(type(user)) return render(request, 'account/profile/addcard.html') What I thought would happen is that I would get the SellerAccount instance with user = SellerAccount.objects.get(user=request.user) but that has proven to be untrue. I wanted to test what I would get when I let that query through with the simple print(type(user)), and it returns <class 'account.models.SellerAccount'>. I'm baffled by this, both because my understanding of Django is not good enough, and because this should work in theory and it doesn't. Since I can't get … -
Send email with django and celery inside docker gives OSError: [Errno 99] Cannot assign requested address
I am trying to send mail through django and celery inside docker, i am using different container for celey and different for django. here is my compose:- version: "3.8" services: # Redis redis: image: redis:alpine container_name: redis expose: - 6379 # Database Postgres db: image: postgres:alpine volumes: - local_pgdata:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db # Migrations migration: env_file: - .env image: app:django volumes: - .:/django command: > bash -c "python manage.py collectstatic --noinput && python manage.py migrate --noinput" depends_on: - db # Django Application app: env_file: - .env build: . volumes: - .:/django image: app:django ports: - "8000:8000" container_name: django_app command: python manage.py runserver 0.0.0.0:8000 # command: gunicorn HopeAndHappiness.wsgi:application depends_on: db: condition: service_started migration: condition: service_completed_successfully # Celery celery: env_file: - .env restart: always image: app:django volumes: - .:/django command: celery -A HopeAndHappiness worker -l DEBUG container_name: celery depends_on: - db - redis - app - migration nginx: image: nginx:latest ports: - 80:8080 volumes: - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro depends_on: - app volumes: local_pgdata: My Dockerfile:- FROM python:slim-buster EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 # Install system packages required by Wagtail and Django. RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ … -
Custom SessionAuthentication logic not working in my Django REST Framework project
So, the problem is with my custom implementation of SessionAuthentication. I researched google and docs trying to find a way to implement a logic of authenticating Custom User by his telegram_id and personal code, which is defined this way: class CustomUser(AbstractBaseUser): telegram_id = models.IntegerField(unique=True) name = models.CharField(max_length=35) surname = models.CharField(max_length=35) is_curator = models.BooleanField(default=False) developer_result = models.CharField(max_length=256, blank=True, null=True) design_result = models.CharField(max_length=256, blank=True, null=True) code = models.CharField(max_length=8, default=12345678) password = None USERNAME_FIELD = 'telegram_id' def __str__(self): return str(self.telegram_id) Then I created a similar to the example in the documentation CustomAuthentication class: class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self, request): telegram_id = request.data.get('telegram_id') code = request.data.get('code') if not telegram_id or not code: return None try: user = CustomUser.objects.get(telegram_id=telegram_id, code=code) # get the user except CustomUser.DoesNotExist: raise exceptions.AuthenticationFailed('Неверный логин или пароль') # raise exception if user does not exist return (user, None) Created a serializer for login: class CustomLoginSerializer(serializers.Serializer): telegram_id = serializers.CharField() code = serializers.CharField() def create(self, validated_data): telegram_id = validated_data['telegram_id'] code = validated_data['code'] user = CustomUser.objects.get(telegram_id=telegram_id, code=code) return user API view, allowing anybody to have access to it: class CustomUserLogin(GenericAPIView): permission_classes = (permissions.AllowAny,) authentication_classes = (SessionAuthentication, CustomAuthentication) serializer_class = CustomLoginSerializer def post(self, request): serializer = CustomLoginSerializer(data=self.request.data) serializer.is_valid(raise_exception=True) user = serializer.save() login(request, user) return Response("Login successful", … -
Cant load an image in Django Application
I'm trying to build an app and I want from views.py to save an image in a specific file and after that call the image from the template using static I try this path_to_save = r"..\AISystem\texttohandwriting\static\result.png" BG.save( rf"{path_to_save}") return render(request, "text_to_handwriting.html", context) as you can see I saved the image that was produced in the static\result.png and it saves correctly since i see the image. < The image changes every time the user enters a text in the HTML file, I do this <img width="400" height="400" src="{%static 'result.png' %}" alt=""> Terminal show this Could not find file. Using default file... [29/Aug/2023 17:39:00] "POST /text_to_handwriting.html HTTP/1.1" 200 992 -
issue with importing image in django project
#home{ background-size: cover; display: flex; flex-direction: column; padding: 3px 200px; height: 921px; justify-content: center; align-items: center; } #home::before { content: ""; position: absolute; background-image: url("{% static 'Image/Bg2.jpg'%}") no-repeat center center/cover; background-size: cover; top: 87px; left: 0; height:840px; width: 100%; z-index: -1; opacity: 0.78; } This is my code in style.css of my Django project. I am unable to import this image when I am running my server. My Project structure looks like this Project 4 |----App1 |--migration |--static | |---CSS | | |---style.css | |--Image | |---Bg2.jpg |--template |---index.html I had two folders in my static folder. My path to the image is ( "My Project/My app/static folder/Image folder/My_image" ). I imported this image in my CSS file. I tried below URLs also background:url("../Image/Bg2.jpg"). I just want my image to be available I run my server localhost:8000/index/ -
solution to use django-advanced-filters in html template instead of django-admin
I'm looking for a solution to using Django-advanced-filters in Django template instead of Django-admin currently Django-advanced-filters can use just in django-admin , I'm looking solution to get query from user based on conditions -
Django Form tag and action attribute
I am not good at English, but no matter how much I try, there is a problem, so I write a question. I wrote it using a translator, but I can read English a little bit. I want login page in Django. I have 2 app. "mysite", "myapp" mysite urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] myapp urls.py from django.urls import path from myapp import views from django.contrib.auth import views as auth_view app_name = 'myapp' urlpatterns = [ path('', views.index), path('result', views.result), path('reuslt2', views.result2), ] myapp views.py from django.shortcuts import render, HttpResponse from django.shortcuts import get_object_or_404, redirect from django.utils import timezone # Create your views here. def index(request): return render(request, 'main_page.html') def login_success(request): #login_info = [request.POST['username'], request.POST['password']] if request.method == 'POST': return HttpResponse('success') #return HttpResponse(login_info[0], login_info[1]) else: return HttpResponse('fail') def result(request): return render(request, 'main_page.html') def result2(request): return render(request, 'temp.html') The login page I want uses two input tags, and the method uses the POST method to get the ID and password input. I connect 127.0.0.1:8000/result. I can see 2 input tags. click submit button. -> connect 127.0.0.1:8000/result2 If the above method is successful, I think it will be possible … -
Cannot override UserCreateSerializer of Djoser
I would like to add additional fields when user registering. I created an app account. Added it to INSTALLED_APPS = [ ... 'account.apps.AccountConfig', ] In account I've created serializers.py from django.conf import settings from djoser.serializers import UserCreateSerializer class CustomUserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): fields = ( settings.LOGIN_FIELD, settings.USER_ID_FIELD, 'password', 'first_name', 'last_name', 'email', ) I've changed SERIALIZERS setting of DJOSER: DJOSER = { 'USER_CREATE_PASSWORD_RETYPE': True, 'SERIALIZERS': { 'user_create': 'account.serializers.CustomUserCreateSerializer', }, } urlpatterns in urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/auth/', include('djoser.urls')), path('api/v1/auth/', include('djoser.urls.authtoken')), ] When I send POST data to http://localhost:8000/api/v1/auth/users/ new user successfully registered. But fields 'first_name', 'last_name' are empty! I think DJOSER SERIALIZERS doesn't see 'user_create': 'account.serializers.CustomUserCreateSerializer'. My question - what I did wrong? How can I override UserCreateSerializer of Djoser? -
Trying to connect django and ms sql 2019 with django-mssql-backend
I've got this error: django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' ENGINE': 'sql_server.pyodbc', pip freeze shows me this: asgiref==3.7.2 distlib==0.3.7 Django==4.2.4 django-mssql==1.8 django-mssql-backend==2.8.1 filelock==3.12.3 mssql-django==1.3 platformdirs==3.10.0 pytz==2023.3 sqlparse==0.4.4 tzdata==2023.3 virtualenv==20.24.3 i tried use 'mssql' engine, but it doesn't work too -
Related drop-down lists in the Django admin panel?
how do I make linked drop-down lists in the Django admin panel? there are 3 models when you add a category to products, for example, electronics, and only what is related to electronics fell out in the subcategory. class Products(models.Model): name = models.CharField(max_length=255, verbose_name='Название') category = models.ForeignKey('Category', on_delete=models.CASCADE, verbose_name='Категория') subcategory = models.ForeignKey('SubCategory', on_delete=models.CASCADE, verbose_name='subКатегория') class Category(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') class SubCategory(models.Model): name = models.CharField(max_length=255, db_index=True, verbose_name='Название') category = models.ForeignKey('Category', on_delete=models.CASCADE) -
Django. Buttons stop working after fetching
I'm trying to fetch text,images from another html file using django and javascript. HTML Code: <body> <nav style="background: #000;"> <div class="top-bar"> <button type="button" id="page1" >Button</button><button type="button" id="page2">Button</button><button type="button" id="page3">Button</button><button type="button" id="page4">Button</button><button type="button" id="page4">Button</button> </div> </nav> <div id="content"> {% block body %} {% endblock %} </div> </body> JS Code: document.addEventListener("DOMContentLoaded",()=>{ const content = document.getElementById("content"); document.getElementById('page1').addEventListener('click', function() { fetch('path/to/index') .then(response => response.text()) .then(data => { content.innerHTML = data; }); }); document.getElementById('page2').addEventListener('click', function() { fetch('path/to/info') .then(response => response.text()) .then(data => { content.innerHTML = data; }); }); document.getElementById('page3').addEventListener('click', function() { fetch('path/to/comms') .then(response => response.text()) .then(data => { content.innerHTML = data; }); }); }) Whenever i fetch the data, my buttons stop working. I've created this file as a test. I'm currently trying to get texts into the content div using sidebar on my main site that im working on. Both files have the same issue. -
how to send post request when browser closing in React
Well, in order to be able to detect the status of browsers, if users are on the site, I want to send a request if they close the browser and change a feature in a model. It should be noted that this model is different from the user model in Django. Also, I'm using Django sessions and SESSION_EXPIRE_AT_BROWSER_CLOSE=True but that's not working. So I use React window.onblur event and that's not working again! I try this code in react but it's not working! let stid:string|null=localStorage.getItem('stationid') useEffect(() => { window.onblur=()=>{ console.log('hello') Api.delete(STATION_ID(stid)).then((res)=>{ console.log(res.data) }).catch(err=>{ console.log(err) }) } return () => { console.log('hello') } }, []) -
Running background tasks in Flask using Django
I have a web application built fully using Flask, at the moment the entire project runs on flask, i'm using many flask libraries for various functionality. However, some of these tasks i am running are very time consuming and take around 5 minutes to finish, and because of this if someone was to run this task and someone else wanted to navigate the website they would be stuck loading while the other lengthy task is done. I'm currently looking for ways to finish running this task in the background so that users can freely navigate the website without being held hostage for 5 minutes while processing is done, I looked into Celery but would rather not use it. Someone instead suggested that I integrate Django to handle this instead, is this feasible, if so how? Here is a quick sample of the current code I have: @app.route("/apple/newoffercodes/<int:appID>", methods=['GET','POST']) @login_required def newoffercodes(appID): application = ApplicationApple.query.filter_by(appleID=appID).first_or_404() package_name = application.appleID form = offerCode() if form.validate_on_submit(): filename = form.file.data result = createSubscriptionOffer(filename) if result == 200 or result == 201: flash("Offer Code Created Successfully","success") return redirect(url_for('offercodes',appID=appID)) else: flash("An error has occurred while creating the offer. Please check Apple Connect.", "danger") return redirect(url_for('offercodes',appID=appID)) return render_template('newOfferCodeApple.html', … -
Sonarqube exection failure while trying to analyse Python code locally on windows
C:\sonar-scanner-5.0.1.3006-windows\bin>sonar-scanner.bat INFO: Scanner configuration file: C:\sonar-scanner-5.0.1.3006-windows\bin..\conf\sonar-scanner.properties INFO: Project root configuration file: NONE INFO: SonarScanner 5.0.1.3006 INFO: Java 17.0.7 Eclipse Adoptium (64-bit) INFO: Windows 10 10.0 amd64 INFO: User cache: C:\Users\AREKAN.sonar\cache INFO: Analyzing on SonarQube server 9.9.0.65466 INFO: Default locale: "en_US", source code encoding: "UTF-8" INFO: Load global settings INFO: Load global settings (done) | time=105ms INFO: Server id: 147B411E-AYos9Bu0eOBihffPYMUp INFO: User cache: C:\Users\AREKAN.sonar\cache INFO: Load/download plugins INFO: Load plugins index INFO: Load plugins index (done) | time=48ms INFO: Load/download plugins (done) | time=313ms INFO: Loaded core extensions: developer-scanner INFO: Process project properties ERROR: Invalid value of sonar.sources for OLU-APP INFO: ------------------------------------------------------------------------ INFO: EXECUTION FAILURE INFO: ------------------------------------------------------------------------ INFO: Total time: 2.546s INFO: Final Memory: 21M/74M INFO: ------------------------------------------------------------------------ ERROR: Error during SonarScanner execution ERROR: The folder 'C:sonar-scanner-5.0.1.3006-windowsbincode' does not exist for 'OLU-APP' (base directory = C:\sonar-scanner-5.0.1.3006-windows\bin) ERROR: I put my django code in a folder and then edited the .property file to point to the folder where my Django code is but when I ran the sonarscan.. i go the error shown -
DRF ModelSerializer implicitly ignore some fields that are not excluded
I have a model: class GeneratedMessage(models.Model): generated_message_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) status = models.CharField(...) message_type = models.CharField(...) ... prospect = models.ForeignKey(to=Prospect...) ai_prompt = models.ForeignKey(to=AiPrompt...) And a model serializer: class GeneratedMessageSerializer(serializers.ModelSerializer): class Meta: model = GeneratedMessage exclude = ['prospect', 'ai_prompt'] read_only_fields = ['__all__'] Actually, I use this serializer inside another one: class GeneratedEmailSerializer(serializers.Serializer): body = GeneratedMessageSerializer() ... This is the way I create a response: class ProspectGenerateMessageAPI(APIView): ... @extend_schema(..., responses={200: GeneratedEmailSerializer}) def post(self, request): ... generated_message.save() response = GeneratedEmailSerializer(data={ ... "body": GeneratedMessageSerializer(generated_message).data }) response.is_valid(raise_exception=True) return HttpResponse.ok(response.data) However, the response has no field body.generated_message_id even though it was never excluded! Other fields like the body.status are presented in the response. Important facts: I find out in the Debug mode that GeneratedMessageSerializer(generated_message).initial_data have a valid id, while GeneratedMessageSerializer(generated_message).data not. Swagger docs generated by @extend_schema are somewhy correct with the field generated_message_id -
page not found while giving path in urls.py of app 'blog-single.html/<int:id>',views.blogsidebar, name='blog-sidebar'
It shows page not found while giving path in urls.py of app 'blog-single.html/<int:id>',views.blogsidebar, name='blog-sidebar' enter image description here It is my urls.py 's paths. Here while I added <int:id > the blog-single.html page started showing page not found enter image description here and it is my views.py's file .....can anyone say what causes for showing this error enter image description here -
Why dosent django find my assets and attachements?
I have a website hosted on centos7 And I want to move it to ubuntu22.04.3 I installed python 3.10.12 and 3.11.4 versions django and all prerequisits I'v changed the apacheconfig file but when I run the server It works but it does not find my assets and attachements here is the output on the stdout: sudo python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). August 29, 2023 - 12:00:53 Django version 3.2.12, using settings 'website.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [29/Aug/2023 12:00:58] "GET /fr/ HTTP/1.1" 200 55434 [29/Aug/2023 12:00:58] "GET /assets/css/default.css HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /assets/css/bootstrap-icons.css HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /assets/css/bootstrap.min.css HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /uploads/2022/12/08/photo1.PNG HTTP/1.1" 404 179 [29/Aug/2023 12:00:58] "GET /uploads/2023/03/17/image35.JPG HTTP/1.1" 404 179 Please any idea might help share if you have a clue I tried modifying the apache2 config file and a lot more. -
Why can't gunicorn utilize more workers (google app engine)?
In documentation you can find https://cloud.google.com/appengine/docs/flexible/python/runtime. It says that not having gunicorn.conf.py that sets multiple workers could increase latency since default worker number is 1 (latency does get high with one worker 800ms). However obeying the recommended gunicorn setup increases the response time by 4 more seconds and sometimes it just fails to deliver. My entrypoint: entrypoint: gunicorn -c gunicorn.conf.py -b :$PORT main:app Entrypoint with one worker: entrypoint: gunicorn -b :$PORT main:app What could be the issue?