Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i put django-multi-captcha-admin in django jazzmin?
i was asking how can i put multi captcha admin in my Admin Login with Jazzmin which is Django Admin Theme??, because i've put the configs from multi captcha admin, but jazzmin doesn't allow me to show up the recaptcha in Login Admin Page i hope can you help me Thanks! i have this INSTALLED_APPS = [ 'jazzmin', 'multi_captcha_admin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'django_recaptcha', 'captcha', ] MULTI_CAPTCHA_ADMIN = { 'engine': 'recaptcha', } JAZZMIN_SETTINGS = { # title of the window (Will default to current_admin_site.site_title if absent or None) obviously the captcha works when i remove the jazzmin from INSTALLED_APP, but when i'm in jazzmin, doesn't show it i don't know why.. i hope you can help me to fix it thanks! greetings -
Google Sheet Formula to Django Logic
I am creating a timesheet for an admin to enter time for users. I am converting this project from Google Sheets to Django. I am stumped to say the least. I am trying to get the total hours to match with the Google Sheet Formula. But it seems that my Django logic is not adding up. Here is the Google Sheet Formula: =(IF((MROUND(F6*24,0.25)-MROUND(F5*24,0.25))>=8,((MROUND(F6*24,0.25)-MROUND(F5*24,0.25)))-0.5,((MROUND(F6*24,0.25)-MROUND(F5*24,0.25))))) All cells (F5 and F6) are replaced with Start Time and End Time. Here is my Django logic. def calculate_total_time(self,start_time, end_time): if start_time is not None and end_time is not None: start_minutes = start_time.hour * 60 + start_time.minute end_minutes = end_time.hour * 60 + end_time.minute if end_minutes < start_minutes: end_minutes += 24 * 60 difference_minutes = end_minutes - start_minutes total_hours = difference_minutes / 60 # Calculate the rounded total hours rounded_hours = math.floor(total_hours * 4) / 4 # Adjust for cases where rounding might go over 8 hours if rounded_hours >= 8: rounded_hours -= 0.5 return rounded_hours else: return 0.00 Some hours display fine with no issues, but then I have hours like these where the logic does not add up. (Pictures for reference) Google Sheet Formula Output: Django Logic Output: I am trying to get the … -
why vercel return an error when deploying django app on it
I am endeavoring to deploy my Django application on Vercel following the method outlined in the video tutorial. However, during the build process, an error is being logged. Regrettably, I am unable to discern the cause of this error. Could someone proficient in this deployment process kindly pinpoint where I may have erred? The Logs: WARN! Due to `builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings Installing required dependencies... Failed to run "pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt" Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [21 lines of output] running egg_info writing psycopg2.egg-info/PKG-INFO writing dependency_links to psycopg2.egg-info/dependency_links.txt writing top-level names to psycopg2.egg-info/top_level.txt Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. … -
Django error while migrating to POSTGRsql cannot drop sequence home_userinformation_id_seq because column id of table home_userinformation requires it
My django application makes migrations successfully but when I try to migrate it, it prompts the following error: raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\shazi\OneDrive\Desktop\arabic\env\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.InternalError: cannot drop sequence home_userinformation_id_seq because column id of table home_userinformation requires it HINT: You can drop column id of table home_userinformation instead. \ from django.db import models class UserInformation(models.Model): username = models.CharField(max_length=50) level = models.PositiveIntegerField(default=1) xp = models.PositiveBigIntegerField(default=0) def update_xp(self, amount): self.xp += amount self.save() # Save the model instance def update_level(self): if self.xp > self.level_up_threshold(self.level): self.level += 1 self.save() def level_up_threshold(self, level): # Indent for class method return level * 100 def __str__(self): return self.username class Module(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) xp_reward = models.PositiveIntegerField(default=0) # XP awarded for completing the module def __str__(self): return self.name class CompletedModule(models.Model): user = models.ForeignKey(UserInformation, on_delete=models.CASCADE) module = models.ForeignKey(Module, on_delete=models.CASCADE) completion_date = models.DateTimeField(auto_now_add=True) # Records date of completion class Meta: unique_together = ('user', 'module') # Ensures a user can't complete a module twice -
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 …