Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to login to Django admin panel after implementing custom user model
I've done for customizing the User model, but I'm unable to log in to the admin panel with the superuser account I created. What could be causing this issue, and how can I resolve it? Any help or guidance would be greatly appreciated. users/user.py from django.contrib.auth.models import AbstractUser from django.db import models from ..managers.user import UserManager class User(AbstractUser): objects = UserManager() manager/user.py from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_superuser(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, email, password, **extra_fields) def create_user(self, email, username=None, password=None, **extra_fields): if not username: raise ValueError('The username field must set') email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self.db) return user user/serializer.py from django.contrib.auth import get_user_model from django.contrib.auth.password_validation import validate_password from rest_framework import serializers # type: ignore # noqa: I201 User = get_user_model() class UserReadSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') class UserWriteSerializer(serializers.ModelSerializer): password = serializers.CharField(validators=[validate_password], write_only=True) class Meta: model = User fields = ('password', 'username') def create(self, validated_data): password = validated_data.pop('password') username = validated_data.get('username') user = User.objects.create_user(username=username, password=password) return user settings/base.py from typing import List DEBUG = True # This should be 'False' in prod mode SECRET_KEY = NotImplemented ALLOWED_HOSTS: List[str] = ['*'] CORS_ALLOW_ALL_ORIGINS = True CSRF_TRUSTED_ORIGINS: … -
OpenLiteSpeed django app broken after ubuntu upgrade
I was running an Ubuntu Image of litespeed django application, https://azuremarketplace.microsoft.com/en-us/marketplace/apps/litespeedtechnologies.openlitespeed-django It was 20.04 LTS, I tried to do a release upgrade which was successful to 22.04 but the OpenLiteSpeed server now fails to run. Steps I already tried: Reinstalled python virtual environment Re-installed the dependencies Tried running the application on 8000 port using python3 manage.py runserver command and it works on the browser as expected updated the vhost file on the Server with the update python runtime path from 3.8 to 3.10 The request keeps on spinning in the browser and after some time errors with 503. There is no entry in the /usr/local/lsws/logs/stderr.log file regarding the 503 error Steps I already tried: Reinstalled python virtual environment Re-installed the dependencies Tried running the application on 8000 port using python3 manage.py runserver command and it works on the browser as expected updated the vhost file on the Server with the update python runtime path from 3.8 to 3.10 -
Django index.html template - menu from queryset
I've got index.html with menu, that is (should be) populated using : {% for category in categories %} Usually, I can return queryset with categories in my view, but as it is index.html and menu, - am I forced to have that query to get categories, in every single view of my app? I think it is not the best approach, but I don't know how to do it correctly. Please help :) -
Styling Django Autocomplete Light
I'm using Django Crispy forms with the tailwind template pack to render out my form, I need autocomplete functionality to be able to search for and select an ingredient. The only viable package I could find is DAL (Django Autocomplete Light). The problem I am facing now is that I can't override the styling so that it looks the same as my other fields. If someone could point me in a direction of how I can achieve this I would be very grateful :) overiding the widget attrs (as shown below) does not do it as this affects the select element which is hidden by DAL my form field: ingredient = forms.ModelChoiceField(queryset=Ingredient.objects.all(), widget=autocomplete.ModelSelect2(attrs={'class': '*my_tailwind_classes*'})) -
Django Rest Framework eventstream endpoint closes immediately after connection
To implement SSE on DRF side I use django-eventstream. I use curl to check if my Django SSE implementation works correct: curl -N -H "Accept: text/event-stream" http://127.0.0.1:8000/api/{uid}/events/ For whatever reason I get only event: stream-open data: That's it, after that stream is closed. I have set up 'Daphne', 'django_grip.GripMiddleware', ASGI. It goes through custom middleware which checks if user has correct token to connect to this stream, sends initial event and closes. Any tips how to solve the issue are appreciated! -
My Django Azure app doesn't fill home/site/wwwroot with app's contents
My Django Azure app doesn't put the app's components in the home/site/wwwroot directory. The problem might lie in that I have renamed the main directory of the app as core. But I have tried to putting gunicorn --bind=0.0.0.0 --timeout 600 core.wsgi in configuration/general settings and this only broke the app and I found in logs that the module core is non-existant. I have also put SCM_DO_BUILD_DURING_DEPLOYMENT = 1 in settings. I still get the start app page instead of my apps' main page. You can see the code here: https://github.com/JJDabrowski/Portfolio Are there any ways to view to logs during the deployment to see what happens that my home/site/wwwroot doesn't have the app's components inside? -
CORS configurations in Django not working in production
I am working on a chat application with Django at the back-end and React at the front-end. Both are hosted on separate domains on vercel. I have added the CORS configurations in the back-end but they don't seem to be working in the production. Following are the CORS configs done in Django: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ALLOWED_HOSTS = ['.vercel.app'] CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ['https://texter-frontend.vercel.app',] Here is one of the requests from the front-end: const backendServerEndpoint = 'https://texter-backend-jp24ejwc8-sourav-pys-projects.vercel.app'; const requestData = { 'phoneNumber' : phoneNumber }; fetch(backendServerEndpoint + '/auth/sendotp/',{ method: "POST", // *GET, POST, PUT, DELETE, etc. mode: "cors", // no-cors, *cors, same-origin credentials: 'include', headers: { "Content-Type": "application/json", }, body: JSON.stringify(requestData), }) .then( response => { if(response.status === 200){ setOtpSent(true); response.json() .then( responseData => { console.log(responseData); if(responseData.newProfile){ console.log("It is a new profile!!!"); setNewProfile(true); } } ) } } ) .catch( error => { console.log(error); } ) This is the error that I am getting in the console: Access to fetch at 'https://texter-backend-jp24ejwc8-sourav-pys-projects.vercel.app/auth/sendotp/' from origin 'https://texter-frontend.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode … -
Deploying my first Django app: seeing the settings site even though the app should be deployed
the deployment process went smoothly thanks to invaluable @PravallikaKV's help 🙏 But even after that I don't see the app but the startup page: I found out that there might be some problems in the folder structure and so I went to my ssh page ( https://.scm.azurewebsites.net/webssh/host ), only to find out that the files are already there, but perhaps in the tmp directory, not in the site/root one. I have added SCM_DO_BUILD_DURING_DEPLOYMENT = 1 at the end of the settings file for my app, but still when I navigate to the top of my website directory and checkout the root folder it's empty ( https://learn.microsoft.com/en-us/answers/questions/778446/django-application-deployed-but-test-page-shows-de ). I couldn't find neither site nor wwwroot inside the site folder and if I understand well from Django tutorial, I should run migrations from that folder. Please help. -
Implement Highlight.js in TextArea
I have a Django app that currently has some tools for the user to try out. I made an implementation of TextFSM and the way its set up is by making a TextArea form where the user can type his code and then it will output the result. Form looks like this: class TextFsmForm(forms.Form): """Form for the TextFsmParserView""" textfsm_template = forms.CharField( widget=CodeTextarea( attrs={ "class": "p-3 form-control bg-transparent resizeable", "placeholder": "TextFSM Template", } ), label="TextFSM Template", required=True, ) raw_text = forms.CharField( widget=CodeTextarea( attrs={ "class": "p-3 form-control bg-transparent resizeable", "placeholder": "Raw Text", } ), label="Raw Text", required=True, ) And the html is like this: <div class="pe-2"> <div class="mb-3 position-relative"> <label class="mb-2 fs-5 display-4" for="{{ form.textfsm_template.id_for_label }}">{{form.textfsm_template.label}}</label> {{ form.textfsm_template }} </div> <div class="position-relative"> <label class="mb-2 fs-5 display-4" for="{{ form.raw_text.id_for_label }}">{{form.raw_text.label}}</label> {{ form.raw_text }} </div> </div> <!-- Rendered output --> <div class="d-flex flex-column"> <p class="fs-5 mb-2 display-4">Result</p> <div id="result" class="p-4 p-md-3 tool-output form-control"> {% if output %}{{output}}{% elif error %}<span class="text-danger">{{error}}</span>{% endif %} </div> </div> Now my problem here is that whenever I try to use either Highlight.js or Prism.js the only hightlight Im getting is the font changing. No colorization or anything. Most relevant post I could find is here but still doesnt … -
Token authentication in django (rest_framework) not working in production environment but works in local machine
when I test my view with a proper token in my local machine it works properly but when I test the view in a production environment with a proper token too I get { "detail": "Authentication credentials were not provided." } . What could be the cause of me having this in error in my production environment? views.py class AdminUserCreateView(APIView): permission_classes = [IsAuthenticated] authentication_classes = [AdminTokenAuthentication] @swagger_auto_schema( request_body=CreateAdminSerializer, responses={ 201: "AdminUser created successfully", 400: "Validation failed", }, ) def post(self, request, *args, **kwargs): serializer = CreateAdminSerializer(data=request.data) if serializer.is_valid(): email = serializer.validated_data.get("email") password = serializer.validated_data.get("password") try: # Check if the email already exists if AdminUser.objects.filter(email=email).exists(): return Response( {"status": "error", "message": "Email already exists"}, status=status.HTTP_400_BAD_REQUEST, ) # Hash the password hashed_password = make_password(password) # Create the AdminUser instance AdminUser.objects.create(email=email, password=hashed_password) return Response( {"status": "success", "message": "AdminUser created successfully"}, status=status.HTTP_201_CREATED, ) except IntegrityError as e: return Response( {"status": "error", "message": "Database integrity error occurred"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) else: return Response( { "status": "error", "message": "Validation failed", "errors": serializer.errors, }, status=status.HTTP_400_BAD_REQUEST, ) middleware.py class AdminTokenAuthenticationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Check if the request path matches the endpoints that require admin token authentication if request.path.startswith("/admin"): return self.process_admin_request(request) # For other … -
Get category id for item from Django url
It looks like something simple and common, but I can't find what's wrong in my implementation. I create a simple item add/edit form in my Django project for items by categories. The form will be located at /<category_id>/add. After filling data on form, it can just get category from category_id. I try to fill this data in form_valid method of FormView, but all I got is error: IntegrityError at /1/add NOT NULL constraint failed: megashop_item.category_id I've tried print("boo") in my form_valid method - nothing is printed, looks like a validation throws exception before. Looks like it's ItemCreateView validation, but how to fix it? How to fix it? All examples are about using functions, not views. models.py class Category(models.Model): title = models.CharField(max_length=200) class Item (models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) forms.py class ItemForm(forms.ModelForm): class Meta: model = Story fields = ["title", "category"] urls.py urlpatterns = [ path("<int:category_id>/add", ItemCreateView.as_view(), name="item-add"), ] views.py class ItemCreateView(LoginRequiredMixin, CreateView): model = Category form_class = CategoryForm class ItemFormView(LoginRequiredMixin, FormView): template_name = "megashop/item_form.html" form_class = ItemForm success_url = reverse_lazy("catalog:index") def form_valid(self, form): instance = form.save(commit=False) instance.contest = Category.objects.get(pk=self.kwargs.get('category_id')) form.save() return HttpResponseRedirect(self.get_success_url()) -
DjangoModelPermissionsOrAnonReadOnly still needs authentication
I encountered this issue even though I didn't set authentication requirements in my settings.py. When I view the /products/ endpoint as anonymous user it still asks for authentication but when I view the endpoint as authenticated user it behaves as expected here's my viewset where I'm using the permission class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter pagination_class = DefaultPagination permission_classes = [DjangoModelPermissionsOrAnonReadOnly] search_fields = ["title", "description"] ordering_fields = ["unit_price", "last_update"] def destroy(self, request, *args, **kwargs): if OrderItem.objects.filter(product_id=kwargs["pk"]).count() > 0: return Response( { "error": "Product cannot be deleted because it is associated with an order item." }, status=status.HTTP_405_METHOD_NOT_ALLOWED, ) return super().destroy(request, *args, **kwargs) here's my settings.py file """ Django settings for storefront project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path from datetime import timedelta # 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-hs6j037urx6iav+7#10%-vu4l4f5@@-1_zo)oft4g7$vf2$jmp" # SECURITY WARNING: don't run … -
Why is username required when I set email as username
I am. trying to create Django backend for my application. For authentication I am using django authentication where I needed to create CustomUser model for my specific use case. After trying to insert new user I am encountering this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "users_customuser_username_key" DETAIL: Key (username)=() already exists. I will add full traceback below. I have also included this line in settings.py AUTH_USER_MODEL = "users.CustomUser" This is my function that I use for creating new user: from .models import CustomUser from .dto import UserRegistrationDto, JWTDto def create_user_in_database(data: UserRegistrationDto) -> JWTDto: user = CustomUser.objects.create(first_name=data.first_name, last_name=data.last_name,birthdate=data.birthdate, email=data.email) user.save() user.set_password(data.password) return user My CustomUser model definition: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): birthdate = models.DateField(null=True, blank=True) email = models.EmailField(unique=True) key = models.PositiveBigIntegerField(default=1,null=False) tier = models.IntegerField(default=1,null=False) used_capacity = models.FloatField(default=0.0,null=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["birthdate","first_name","last_name"] My DTO class: class UserRegistrationDto(ModelSchema): class Meta: model = CustomUser fields = ["first_name","last_name","birthdate","email","password"] Full traceback: duplicate key value violates unique constraint "users_customuser_username_key" DETAIL: Key (username)=() already exists. Traceback (most recent call last): File "//Caches/pypoetry/virtualenvs/backend-y-HyWMBZ-py3.11/lib/python3.11/site-packages/django/db/backends/utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "users_customuser_username_key" DETAIL: Key (username)=() already exists. The above exception was the … -
Getting wrong SSE response from the server
Developing the project with Django. DRF installed. Some processin the backend generating a log file. I am looking at the end of the file for target strings. When target string was caught, it has to be shown on HTML user page. Everything happens in dynamics. urls.py path('api/log-stream/', LogStreamAPIView.as_view(), name='log_stream'), LogStreamAPIView class LogStreamAPIView(APIView): def get(self, request): def stream_log(): f = subprocess.Popen(['tail', '-F', rcvenot_log], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p = select.poll() p.register(f.stdout) while TEST_IN_PROGRESS: if p.poll(0.1): new_line_log = f.stdout.readline().decode('utf-8').strip() for target_line in RCV_SCENARIO: if target_line in new_line_log: yield f"event: {new_line_log}\n\n" return StreamingHttpResponse(stream_log(), content_type='text/event-stream') Script on the user HTML page <div style="width: 200px; height: 200px; overflow-y: scroll;"> <ul id="logList"></ul> </div> <script> document.addEventListener("DOMContentLoaded", function() { var logList = document.getElementById('logList'); function updateLog(newLine) { var listItem = document.createElement('li'); listItem.textContent = newLine; logList.appendChild(listItem); } var source = new EventSource('/api/log-stream/'); source.onmessage = function(event) { updateLog(event.data); }; }); </script> I see the strigns via API mysite.ru/api/log-stream/. Some strings event: 2024.03.22 16:16:13:016[INFO ][Thread-0] ************************* - 2 But I don't see them on HTML page. In browser console I see the response code 406: GET 127.0.0.1:8000/api/log-stream 406 (Not Acceptable) In Response see {"detail":"The \"Accept\" request header could not be satisfied."} I have tried throw data in different formats f"event: {new_line_log}\n\n" or f"data: {new_line_log}\n\n". … -
How to ensuring Source Code secure for Python Applications on Client Systems
I’m developing python django web application based on the client requirement and configuration. I was to prevent the client from accessing to my source code and tampering with my code. I tried encoding my source code into machine code but issue is that it can be decoded to normal code Would appreciate it if anyone can provide me advice and guidance on how to achieve my goal is securing source code -
Django / UploadFileForm only provides No valid form?
i try to create a simple file-upload funcionality with Django using the following code / files - Its more or less taken from this example: https://docs.djangoproject.com/en/5.0/topics/http/file-uploads/ forms.py: from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() views.py: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import UploadFileForm import os import sys def handle_uploaded_file(f): path = os.path.abspath(os.path.dirname(sys.argv[0])) fnFile = os.path.join(path, "gpp", "FILES", "QUESTIONS", "someFile.xyz") print(fnFile) with open(fnFile, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def home(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) print(request.POST) print(request.FILES) if form.is_valid(): print(f"Valid form") handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: print("No valid form") else: form = UploadFileForm() return render(request, 'home.html', {'form': form}) Generally the form looks fine and i can choose the file: But when i enter something it doesn´t work seeing the following in the log: [23/Mar/2024 10:02:35] "GET / HTTP/1.1" 200 1777 <QueryDict: {'csrfmiddlewaretoken': ['HWaddf1sBsKJc1k4CY9LiijIv1VAlxjWkRoFRixEP12rNDYyIx6zRYFC2MvPKIFm'], 'title': ['Test'], 'file': ['gpt.zip'], 'save': ['']}> <MultiValueDict: {}> No valid form [23/Mar/2024 10:04:33] "POST / HTTP/1.1" 200 1869 So it seems that request.FILES is for whatever reason empty? Why is this not working as intended? -
AlpineJS not initializing in dynamically loaded content
I am creating a custom searchable select widget in my django application. When returning the template normally all is well, however Alpine is not initializing when I render this field dynamically inside a modal. I use HTMX to make the ajax request; Django responds with a template and the template gets inserted into the DOM/modal. Things I've tried Adding my Alpine.data's data directly into the x-data. This works but there is quite a lot a would like to avoid it if possible Hacky ways to try initialize Alpine but does not work (maybe I've missed something) Hooking into HTMX beforeSwap event to try load the JS before the template (no dice) If anyone knows how to remedy this it would be greatly appreciated Template <div x-data="autocomplete" x-init="init('{{ widget.value }}')" class="relative"> # template stuff... </div> Script document.addEventListener('alpine:init', () => { Alpine.data('autocomplete', () => ({ open: false, selectedValue: '', init(value) { if (!['None'].includes(value)) { this.selectedValue = value; } }, # functions used inside the template... })); }); -
Django Payment Module Error Not successfully accepting payment
This is my razorpayDemo.html file i cannot be able to successfully do the payment as it is not process and after clicking on the success the button it show the page error and not the message of order successfully placed. Also in my razorpay options UPI QR option is not showing too in testing mode of it? -
Problems with deploying my first Django app on Azure
I have tried different approaches, but none of them works. I still get the: ERROR: No matching distribution found for Python==3.9.18 Or other version I have been trying to use. I tried: Installing the version defined in requirements.txt with Set up Python process: - name: Set up Python uses: actions/setup-python@v3 with: python-version: '3.11.3' (the base version for this app was 3.11.3), changing the requirements.txt to match the version that I found from the Action logs in GitHub: Python Version: /opt/python/3.9.18/bin/python3.9 And then checking which version I have installed locally and trying that one (it's 3.10.1). Each time I get the same error but with different version. Please help. You can browse the full approach here: https://github.com/JJDabrowski/Portfolio -
The media files are not being served in the dockerized django-react-postgresql portfolio from the database
I am building a dockerized personal portfolio using Django, React and PostgreSQL. The issue is, the images I am using are not found by the server in the deployed environment. I am using digitalocean to deploy my portfolio by creating a droplet. I have already uploaded the images in django admin and I am fetching those via API in the react-frontend. This is working fine in the local environment, but the files are not found by the server in the deployed environment. I have tried using NginX for this as well but the issue persists. When I tried to locate that image via django admin panel again, status code 404 is there. Not Found The requested resource was not found on this server. By this, at least I understood that the images I uploading to django admin are not being done successfully. However, when I check the media/images folder, inside the linux server, I can see all uploaded images. stored media files. I am using media_url in settings.py like this: BASE_DIR = Path(__file__).resolve().parent.parent # For the media files MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' I have tried to use NginX by installing it in the droplet and the … -
after using login(request) to create a session in my login view, the session is lost when i access another view in Django
I'm trying to create an API client server model in Django, but every time i log into a user in my login view. When i need to use the information and session from the login, for some reason it gets reset to AnonymousUser in my stories view. And if i use @login required it just redirects me to the login page as if i didn't just authorize and create a session with the user moments ago. Here is my views.py: @csrf_exempt def login_view(request): if request.method == 'POST': payload = request.POST # Validate payload keys if 'Username' not in payload or 'Password' not in payload: return JsonResponse({'message': 'Username or password missing'}, status=400) username = payload['Username'] password = payload['Password'] user = authenticate(request, username=username, password=password) if user is not None: # Log the user in and store session data login(request, user) return JsonResponse({'message': 'Login successful', 'user_id':user.id}, status=200) else: # Incorrect username or password return JsonResponse({'message': 'Incorrect username or password'}, status=401) @csrf_exempt @login_required def stories(request): if request.method == 'POST': if request.user.is_authenticated: print(request.user.username) # Retrieve data from the POST request headline = request.POST.get('Headline') category = request.POST.get('Category') region = request.POST.get('Region') details = request.POST.get('Details') # Get the current user's author object author = Author.objects.get(user=request.user.id) author_name = author.name … -
Getting Forbidden You don't have permission to access this resource error while depolye django project with apache and mod_wsgi
Here is my error from error_log [Fri Mar 22 16:00:09.035343 2024] [wsgi:info] [pid 63294:tid 63294] mod_wsgi (pid=63896): Process 'swpdoc' has died, deregister and restart it. [Fri Mar 22 16:00:09.035428 2024] [wsgi:info] [pid 63294:tid 63294] mod_wsgi (pid=63896): Process 'swpdoc' terminated by signal 1 [Fri Mar 22 16:00:09.035443 2024] [wsgi:info] [pid 63294:tid 63294] mod_wsgi (pid=63896): Process 'swpdoc' has been deregistered and will no longer be monitored. [Fri Mar 22 16:00:09.036602 2024] [wsgi:info] [pid 63897:tid 63897] mod_wsgi (pid=63897): Starting process 'swpdoc' with uid=48, gid=48 and threads=15. [Fri Mar 22 16:00:09.039512 2024] [wsgi:info] [pid 63897:tid 63897] mod_wsgi (pid=63897): Python home /opt/Production/swpdoc/venv311. [Fri Mar 22 16:00:09.039593 2024] [wsgi:info] [pid 63897:tid 63897] mod_wsgi (pid=63897): Initializing Python. Python path configuration: `` ` ``` `PYTHONHOME = '/opt/Production/swpdoc/venv311' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = '/opt/Production/swpdoc/venv311/lib64/python3.11' sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/opt/Production/swpdoc/venv311' sys.base_exec_prefix = '/opt/Production/swpdoc/venv311' sys.platlibdir = 'lib64' sys.executable = '/usr/bin/python3' sys.prefix = '/opt/Production/swpdoc/venv311' sys.exec_prefix = '/opt/Production/swpdoc/venv311' sys.path = [ '/opt/Production/swpdoc/venv311/lib64/python311.zip', '/opt/Production/swpdoc/venv311/lib64/python3.11', '/opt/Production/swpdoc/venv311/lib64/python3.11/lib-dynload', ]``` Here is my httpd.conf ` WSGIScriptAlias / /opt/Production/swpdoc/techdocsweb/swpdoc/wsgi.py WSGIApplicationGroup %{GLOBAL} <Directory /opt/Production/swpdoc/techdocsweb/swpdoc> <Files wsgi.py> Require all granted </Files> … -
Python 3.12 pip install mod_wsgi fails
I am trying to deploy Django rest framework on my Debian 10 server. I am using Apache2 but he keeps crashing because its not using the right python version. I am using python3.12 version for my project : python --version Python 3.12.2 But Apache2 is running with python3.7 so its crashing because it cant find Django Module Apache/2.4.38 (Debian) mod_wsgi/4.6.5 Python/3.7 configured I tried to install mod_wsgi with pip but I keep getting this error : /usr/bin/ld: final link failed: nonrepresentable section on output collect2: error: ld returned 1 exit status error: command '/usr/bin/gcc' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mod_wsgi Failed to build mod_wsgi ERROR: Could not build wheels for mod_wsgi, which is required to install pyproject.toml-based projects Thanks to everyone fo your time ! I tried everything I found on existing topics. I am expecting a solution to be able to install mod_wsgi and use the right python version on my apache2 server -
cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="Failed to create consumer: sasl.username and sasl.password must be set"}
I'm trying to build this Microservices project But get this error on consumer.py and also vsc says its unable to import confluent_ Here´s the code for consumer.py: import os import json import django from confluent_kafka import Consumer from rest_framework.exceptions import ValidationError os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") django.setup() consumer = Consumer({ 'bootstrap.servers': os.environ.get('KAFKA_BOOTSTRAP_SERVER'), 'security.protocol': os.environ.get('KAFKA_SECURITY_PROTOCOL'), 'sasl.mechanism': 'PLAIN', 'sasl.username': os.environ.get('KAFKA_USERNAME'), 'sasl.password': os.environ.get('KAFKA_PASSWORD'), 'group.id': os.environ.get('KAFKA_GROUP'), 'auto.offset.reset': 'earliest' }) consumer.subscribe([os.environ.get('KAFKA_TOPIC')]) while True: msg = consumer.poll(1.0) if msg is None: continue if msg.error(): print(f"Consumer error: {msg.error()}") continue if msg is not None and not msg.error(): topic = msg.topic() value = msg.value() data = json.loads(value) print(f'Got this message with Topic: {topic} and value: {value}, with Data: {data}') if topic == os.environ.get('KAFKA_TOPIC'): if msg.key() == b'create_user': try: print(f"Order created successfully for user {data['userID']}") except ValidationError as e: print(f"Failed to create order for user {data['userID']}: {str(e)}") consumer.close() Here's producer.py: from confluent_kafka import Producer import os producer= Producer({ 'bootstrap.servers':os.environ.get('KAFKA_BOOTSTRAP_SERVER'), 'security.protocol':'SASL_SSL', 'sasl.mechanism': 'PLAIN', 'sasl.username':os.environ.get('KAFKA_USERNAME'), 'sasl.password':os.environ.get('KAFKA_PASSWORD'), }) I have tried downgrading my Python image from 3.12 to 3.10 but still doesnt work tried changing this FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app/ CMD python manage.py runserver 0.0.0.0:8000 -
Why do I receive 403 error while sending a post request using axios in my react file? And how should I code a sign up page from scratch?
I'm trying to code a sign up page in my django project. I have two apps named "api" and "frontend". I really am not sure if I'm doing it correctly but my main idea is to have a registeration form in http://127.0.0.1:8000/sign-up so that when the user presses the submit button, it would send a post request and my CreateUserView class in api/views.py would get that and the new user would be registered. frontend/urls.py: from django.urls import path from .views import index from api.views import RegisterView urlpatterns = [ path('sign-up', index), path('register', RegisterView.main), ] frontend/views.py: from django.shortcuts import render def index(request, *args, **kwargs): return render(request, 'frontend/index.html') frontend/src/components/App.js: import SignUp from "./SignUp"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import { render } from "react-dom"; function App() { return ( <div> <BrowserRouter> <Routes> <Route path="/sign-up" element={<SignUp />} /> </Routes> </BrowserRouter> </div> ); } export default App; const appDiv = document.getElementById("app"); render(<App />, appDiv); frontend/src/components/SignUp.js: import React, { Component, Fragment, useState } from "react"; import axios from "axios"; function SignUp() { const [gmailAdress, setGmailAdress] = useState(""); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); return( <Fragment> <div> <button onClick={() => axios.post("/sign-up", { method: "POST", headers: { "Content-Type": "application/json" }, …