Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Comment utiliser efficacement les templates dans Django pour une gestion claire et modulaire des pages?
i want to link my backend with python-django with Html files , there is any one can give me his code or example or give me any idea to do this and thank you i want to link my backend with the html files , templates in django -
How can I schedule the deletion of user_club?
I'm trying to implement the following logic: When the user clicks to delete a user_club, a prompt will appear allowing the user to undo this request. If they don't take any action within 5 seconds, we'll proceed with the deletion. Alternatively, if the user performs an undo action, I'll cancel the deletion request in the database. I'm trying to implement using PeriodicTask. However, I haven't been able to complete it yet. Please help me solve the issue I'm facing. Thank you in advance. This is what I've been trying to accomplish, but it hasn't been successful yet. models.py class UserClub(ItemBase): user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_club') club = models.ForeignKey(Club, on_delete=models.CASCADE) roles = models.ManyToManyField(Role) membership_id = models.CharField(max_length=255, blank=True, null=True) membership_expiry_date = models.DateField(max_length=255, blank=True, null=True) subscription = models.ForeignKey(to=Subscription, on_delete=models.SET_NULL, blank=True, null=True, related_name='user_club_subscription') default = models.BooleanField(default=False) reputation_point = models.PositiveIntegerField(default=0) class Meta: db_table = "sport_user_club" verbose_name = 'User Club' verbose_name_plural = 'User Club' views.py def destroy(self, request, *args, **kwargs): user_club = self.get_object() task = task_schedule_del_user_club.apply_async(args=[user_club.uuid], countdown=10) self.response_format['data'] = { "task_id": task.id } self.response_format['message'] = "Club will be deleted after 5 seconds" return JsonResponse(data=self.response_format, status=status.HTTP_200_OK) @swagger_auto_schema(methods=['post'], request_body=UndoDeleteClubProcessSerializer) @action(methods=['post'], detail=False, url_path="undo-request", url_name='undo-request') def undo_request_remove_club(self, request, *args, **kwargs): serializer = UndoDeleteClubProcessSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer_data = serializer.validated_data if serializer_data['is_undo_request']: try: … -
Why does evaluating enviroment variable in setting.py does not work?
I set an environment variable here ~/.bashrc by adding export DJANGO_DEVELOPMENT='True' the committing the changes with source ~/.bashrc Then I checked if the value was correctly wrote with echo $DJANGO_DEVELOPMENT -->RESULT: true Now I'm simply triyng to accede this variabile during the server launch, so Django can figure out I'm in development and override the settings.py file with a settings_dev.py file. The code doing this in setting.py is: import os if os.getenv('DJANGO_DEVELOPMENT') == 'true': from .settings_dev import * The problem is that the server is always executed with DEBUG = False so I know as a fact that python is not reading properly the env. variable. I also double checked by putting a print(os.getenv('DJANGO_DEVELOPMENT')) but it's always None. Someone have any idea where my error is? Thanks in advantage. -
Cannot display as a guest user in ecommerce site in Python+Django
I was following a YouTube tutorial of Dennis Ivy,(https://www.youtube.com/playlist?list=PL-51WBLyFTg0omnamUjL1TCVov7yDTRng), where number of items in "cart-icon" and total amount information is rendered. Image of how it should be: correct_rendering Image of how it is: error_rendering In my case, those are not rendered. I am not sure what went wrong. I tried to search the issue in chatGpt, but couldn't solve the problem. Below is my code: views.py from django.shortcuts import render from django.http import JsonResponse import json from .models import * import datetime def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items # Corrected: Call the method to get cart items else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False} cartItems = order['get_cart_items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() # total = sum(item.product.price * item.quantity for item in items) cartItems = order.get_cart_items # Corrected: Call the method to get cart items else: try: cart = json.loads(request.COOKIES['cart']) # Use .get() to avoid KeyError # cart = json.loads(request.COOKIES.get('cart', '{}')) # Use .get() to avoid KeyError except : # json.JSONDecodeError: … -
When run the be --version give me error of the ModuleNotFoundError: No module named 'imp'
Full error: Traceback (most recent call last): File "", line 198, in _run_module_as_main File "", line 88, in run_code File "C:\Users\arsalan\AppData\Local\Programs\Python\Python312\Scripts\eb.exe_main.py", line 4, in File "C:\Users\arsalan\AppData\Local\Programs\Python\Python312\Lib\site-packages\ebcli\core\ebcore.py", line 16, in from cement.core import foundation, handler, hook File "C:\Users\arsalan\AppData\Local\Programs\Python\Python312\Lib\site-packages\cement\core\foundation.py", line 11, in from ..core import output, extension, arg, controller, meta, cache, mail File "C:\Users\arsalan\AppData\Local\Programs\Python\Python312\Lib\site-packages\cement\core\extension.py", line 8, in from imp import reload # pragma: no cover ^^^^^^^^^^^^^^^^^^^^^^ ModuleNotFoundError: No module named 'imp' I try a lot and even uninstall and reinstall the package it doesn't work. -
Django UserViewSet not setting username and slug despite email being provided
I have a Django UserViewSet where I'm trying to create a new user along with an associated API key. However, despite providing the email, the username is always None, and the slug field is not being created. Additionally, the APIKey object is not being created. Here's my code: class UserViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = User.objects.all() serializer_class = UserSerializer def post(self, request): serializer = self.get_serializer(data=request.data) user = self.get_object() if serializer.is_valid(raise_exception=True): timezone.activate("UTC") api_key = create_hex_key(20) api_key_expiry_date = timezone.now() + timedelta( days=365242, milliseconds=0 ) user.email = user.email.lower() user.username = user.email.lower() if user.email else None user.first_name = user.first_name.lower() if user.first_name else None user.last_name = user.last_name.lower() if user.last_name else None if user.first_name and user.last_name: random_string = generate_random_string() slug = slugify(f"{user.first_name} {user.last_name} {random_string}") while User.objects.filter(slug=slug).exists(): random_string = generate_random_string() slug = slugify( f"{user.first_name} {user.last_name} {random_string}" ) user.slug = slug user.set_password(serializer.validated["password"]) APIKey.objects.create( user=user, name="Default Key", api_key=api_key, expiry_date=api_key_expiry_date.isoformat(), ) user.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And here's my serializer: class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(validators=[]) password = serializers.CharField(validators=[]) class Meta: model = User fields = ["email", "first_name", "last_name", "password"] Despite providing the email in the request data, the username remains None, and the slug is not being created. Additionally, the APIKey object is not being created. What … -
Django Form Error "This field is required." only when trying to retrieve random objects
I get the form error "This field is required." only when trying to retrieve random objects like this: pks = list(QuizQuestion.objects.values_list('pk', flat=True)) random_pks = random.sample(pks, 2) questions = QuizQuestion.objects.filter(pk__in=random_pks) When I am using: questions = QuizQuestion.objects.all() everything works fine. This is the QuizForm: class QuizForm(forms.Form): """QuizForm used to display questions with their options.""" def __init__(self, *args, **kwargs): questions = kwargs.pop('questions') super(QuizForm, self).__init__(*args, **kwargs) for question in questions: choices = [ ('option1', question.option1), ('option2', question.option2), ('option3', question.option3), ('option4', question.option4), ] self.fields[str(question.id)] = forms.ChoiceField( label=question.question_text, choices=choices, widget=forms.RadioSelect(attrs={'class': 'form-check-input'}) ) And this is the html form: <form method="post"> {% csrf_token %} {% for field in form %} <div> <label class="question">{{ field.label }}</label> {% if field.errors %} <ul class="errors"> {% for error in field.errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} <div> {% for choice in field %} <label class="form-check-inline"> {{ choice }} </label> {% endfor %} </div> </div> {% endfor %} <button type="submit">Submit</button> </form> I also tried other methods for getting the random objects from here: Django get a random object and https://books.agiliq.com/projects/django-orm-cookbook/en/latest/random.html. I think the problem is within the QuizForm but i cannot figure out where. -
Is it worth studying django in 2024
I am a novice web developer and recently finished learning python, now I want to move on and try to make the first real project with a working backend. After reading about different frameworks, I liked Django. But recently, one of my friends told me that django is a big Clumsy machine, and if I really want to do backend, then it's better to study node.js or the same flask. I have not found any information from professionals on the Internet. And I decided to ask here, is django really so slow and outdated, and is it worth starting to study it now if I want to be competitive in the market? Tried to learn Django. Expecting good workplace. -
Django some URLs 301ing to home on Production only (NGINX, GUnicorn)
In production, some of my URLs work, some dont and redirect to home / the main site URL. So, I have a site up and running in Production. I use a NGINX load balancer with 3 x NGINX reverse proxy with GUnicorn VMs running the app. The app includes the following in its URL file: path("interest/", view=SDInterestView.as_view(template_name="sd/interest.jinja2"), name="sd_intresse"), path("interesta/", view=SDInterestViewA.as_view(template_name="sd/interest.jinja2"), name="sd_intressea"), path("interestcopy/", view=SDInterestView.as_view(template_name="sd/interest.jinja2"), name="sd_intresse_copy") These are base level URLs. so www.site.com/intresse/ etc... SDInterestView and SDInterestViewA are copy paste code - other than the class name. So - interest/ works. Neither interesta/ or interestcopy/ work in production. Everything works AOK with RunServer or runserver_plus locally in dev. If I access the back end python session of one of the VMs, I can resolve the URL and see for all three the correct attributes for which view they are going to execture. The three URLs all show in manage.py show_urls. I am at a loss as to how to track down what the issue is. At the moment I can not see to add in any base level URLs and get them to work. If I add urls to the apps individual URL files, these show and work AOK - but - … -
Django static files showing ONLY if debugger is started (with DEBUG=True)
I am using daphne as Django server with the integration from daphne to runserver in settings.py I have a strange error since yesterday with static files with DEBUG=True, (so, no, it's not another case of static files not found when DEBUG=False ! ;) They don't show up when I'm running python manage.py runserver but when I run the app using the debugger from VS Code, then they show up. So my setup is working in some way but only under debugging... In settings.py, I have: STATIC_ROOT = BASE_DIR / 'static' STATIC_URL = 'static/' INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ] my launch.json is: { "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": ["runserver"], "django": true, "autoStartBrowser": false, "justMyCode": false, } ] } so it also runs the same command (runserver). The static files are stored in the static// directory of each app. Any idea? -
Django test views code:error database "test_postgres" already exists
I want to test my website and I created a tests folder inside my app and created files for testing models…, I ran the test URLs and it was successful but I faced a problem with views, models, and forms tests, “database "test_postgres" already exists Type 'yes' if you would like to try deleting the test database 'test_postgres', or 'no' to cancel”, I’m afraid to delete something important so how can fix the problem ( I used Supabase hosted my Postgres database). I tried to ran the views and models but I faced this problem what should I do to solve this problem -
Changes in html without refreshing(ajax problem)
I got problem or i kinda don't understand how ajax works. I want after clicking button to add user in likes column in datatable, and then pass variables in json again to ajax which one change elements in html file. All without refreshing. i'm stuck. Ajax works with adding, deleting user, but don't know how to return json and change elements in html. urls.py urlpatterns = [ path('',views.logout_view, name = 'logout'), path('like/<int:pk>', views.commLike, name="comm_like"), ] views.py @login_required def commLike(request, pk): comm_id = request.POST.get('comm_id') comm = Comment.objects.get(comment_id=comm_id) user_name = request.POST.get('user') user_email = request.POST.get('email') profile = User.objects.get(email=user_email ) if not User.objects.get(email=user_email): User.objects.create(email=user_email,name=user_name) if profile in comm.likes.all(): comm.likes.remove(profile) is_liked = False else: comm.likes.add(profile) is_liked = True response = {} response['is_liked'] = is_liked response['total_likes'] = comm.total_likes() # response_data[is_liked,comm.total_likes()] # return render(request, 'show_post.html', { 'is_liked': is_liked, 'total_likes': comm.total_likes()}) return JsonResponse(response) show.html <form action= "{% url 'comm_like' pk=cs.comment_id %}" id=like-butt class="like-button" method="post" > {% csrf_token %} <input type="hidden" name="user" value="{{user}}"> <input type="hidden" name="email" value="{{user.email}}"> <input type="hidden" name="comm_id" value="{{ cs.comment_id }}"> <button type="submit" id='comm_like' value="{{ cs.comment_id }}" class="comment-rating"> <img src="/static/img/thumb_up.png" style="height:2rem;width:2rem;"> </button> </form> script.js $('#like-butt').on('submit',function(e){ e.preventDefault(); console.log("form submitted!") comm_like(); }); function comm_like() { console.log("create post is working!"); const email = $('input[name="email"]').val(); const user = $('input[name="user"]').val(); const comm_id … -
How to merge different models in Django?
I have huge concern about merge two or more models in Django. First, there are 9 models in models.py. (just structure) model A (fields: user, AA(foreign key), created_at) model AA (fields: user, title, content) model AAA (fields: AA(foreign key), theme_name) model B (fields: user, BB(foreign key), created_at) model BB (fields: user, title, content) model BBB (fields: BB(foreign key), theme_name) model C (fields: user, CC(foreign key), created_at) model CC (fields: user, title, content) model CCC (fields: CC(foreign key), theme_name) And I want to merge model A, model B, model C, ordered by 'created_at' with Pagination and filter(with theme_name). I searched for how to merge, but there seemed to be no way other than using annotate to align and merge all types and quantities of fields. However, when additional models created later, if I use annotate at that time, it is expected that the annotated fields will increase too much and it will take more time. What should I do? -
CSS-Grid design choice
I am new to web development and I have a design choice question. I am developing a game where students can learn how to multiply. Now I run into a problem regarding displaying the multiplication. I am not sure on how to format the individual input cells for a multiplication since. The following picture might make my problem a little bit more clear. Since I don't know how many or if any fields(white boxes) and carrys(red boxes) occur I am not sure how to go from here. I am using Django and I have tried to create a grid(not a css grid) of all possible boxes for that calculation and set the display flag to true if that box is neccesary for my calculation. Doing this it did not feel right. There must be an easier way. Would css-grid be the right choice for this type of problem? So I just pass all my boxes to the view and the css will handle the rest. Thanks in advance -
How can I send data from server to frontend
I try to make a project with django and vue.js In vue.js I write this code <tbody v-if="!hrmsActive"> <tr v-for="(holiday, index) in personLeave" :key="index"> <th scope="row"> <!-- {{ index + 1 }} --> {{ personLeave.current_page * perPage - perPage + index + 1 }} </th> <td> {{ holiday.holidays_start_date .split("-") .reverse() .join("-") }} </td> <td> {{ holiday.holidays_end_date .split("-") .reverse() .join("-") }} </td> <td>{{ holiday.holiday_type_name }}</td> <td v-if="holiday.comments"> {{ holiday.comments }} </td> <td v-else> - </td> <td v-if="holiday.on_holidays" class="fas fa-check" style="color:green" ></td> <td v-else class="fas fa-times" style="color:red"></td> </tr> </tbody> and async fetchPersonHolidays() { const filterUrlParams = new URLSearchParams(); Object.entries(this.personLeave).forEach(([key, values]) => { if (values) { if (Array.isArray(values)) { values.forEach((value) => { filterUrlParams.append(key, value); }); } else { filterUrlParams.append(key, values); } } }); await session .get(`api/person/${this.$route.params.id}/holidays/?${filterUrlParams.toString()}`) .then((resp) => { this.personLeave = resp.data; console.log(resp.data) }).catch((e) => { console.log(e.response.data); }); and I try to send data from server in frontend and data don't appear and the error message in the page is TypeError: holiday.holidays_start_date is undefined. What can I do in order to solve this? -
login and my profile api binding in django template
this is my login api view. i am using adminlte for frontend to develop admin panel class LoginView(APIView): @extend_schema(request={'email', 'password'}) def post(self, request): email = request.data.get('email') password = request.data.get('password') remember_me = request.data.get('remember_me') user = authenticate(email=email, password=password) if user: # Set the token expiration based on remember_me option if remember_me: token_lifetime = timezone.now() + timezone.timedelta(days=30) # Long-lived token else: token_lifetime = timezone.now() + timezone.timedelta(minutes=24) # Short-lived token # Generate or retrieve token for the authenticated user token, _ = Token.objects.get_or_create(user=user) token.created = timezone.now() token.expires = token_lifetime user.token = token.key user.last_login = timezone.now() user.save(update_fields=['token', 'last_login']) token.save() return Response({ 'success': True, 'user_id': user.id, 'email': user.email, 'token': token.key}, status=status.HTTP_200_OK) else: return Response({ 'success': False, 'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) this is my frontend view in django. def login_view(request): if request.method == 'POST': data = { 'email': request.POST['email'], 'password': request.POST['password'] } csrf_token = request.COOKIES.get('csrftoken') headers = {'X-CSRFToken': csrf_token} response_content, status_code = Http.post(request, f"{settings.API_URL_V1}/login", data=data, headers=headers) if status_code == 200: token = response_content.get('token') if token: request.session['token'] = token messages.success(request, 'Logged in successfully') return redirect('dashboard') else: if not data['email'] and not data['password']: messages.error(request, 'Email and Password cannot be Empty!') elif not 'password' or len('password') < 8 or not re.search("[!@#$%^&*()-_=+{};:,<.>]", 'password') or not re.search("[0-9]", 'password'): messages.error(request, 'Password must be … -
Django: Add values from dict Queryset
I have this entry monitoring table that has multiple dates and time values. I wanted to get total number of entry every month, that has multiple entry every day per user. I used this line: stats=EntryMonitoring.objects.filter(student_id=user).annotate(month=TruncMonth('date')).values('month').annotate(total=Count('id')) The results is: <QuerySet [{'month': datetime.date(2024, 3, 1), 'total': 25}, {'month': datetime.date(2024, 4, 1), 'total': 1}]> I view the data by using this {% for obj in stats %}{{ obj.total }}{% endfor %} So I got 251. I want to add the total values like 25 and 1, that would be a total of 26 entry for the month. Or I can make the total entries per day. -
Can't log in in django adminstrator interface with my custom backend
I've replaced default backend system with my custom one #overriding authentication method to use email instead of an username. class EmailBackend(ModelBackend): def authenticate(self, request, email = None, password = None): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None if user.check_password(password): return user return None and edited settings.py according to the docs AUTH_USER_MODEL = "accounts.User" AUTHENTICATION_BACKENDS = ["accounts.backends.EmailBackend"] User model itself class User(AbstractUser): email = models.EmailField(max_length=64, unique=True) courses = models.ManyToManyField(Course, blank=True) The problem is that I can login with the email in my html login form, but can't do the same thing in django admin interface. What I've tried so far: Deleted migrations folder with the database itself and then making migrations and migration Restarting the server Creating new superuser -
how to get endpoints framework mobile api request with protorpc message in django restframe work or django view
my code writen in py2.7 in google app engine and i am using endpoint framework for mobile. now my mobile team has endpoint java create lib from py2.7 and they hit the api with the help of that lib I am using this code in py2.7 to get the request data @endpoints.method(UserDetail, UserDetail, http_method='POST', name = 'user.authenticate') def authenticate_user(self, request): print(request.user_detail) print(request.abc) now in django i try all APIView def post(self,request,*args, **kwargs): but in request i didnot get data i try this code also but did not get data class authenticate_user(View): def post(self, request, *args, **kwargs): data = request.body header = request.META # data = data.decode('utf-8') # post_data = json.loads(data) print('----------------') print('-request.GET-') print(request.GET) print('-request.GET-') print('-request.FILES-') print(request.FILES) print('-request.FILES-') print('-META-') print(header) print('-.META-') # print('-post_data-') # print(post_data) # print('-post_data-') print('-request.POST-') print(request.POST) print('-request.POST-') print('-request.headers-') print(request.headers) print('-request.headers-') print('----------------') return JsonResponse({'success':"hiiii"}) i am geting this. I don't want to change mobile code i want to convert my code in python3 with django could any one help me. Now endpoint does not sport py3 May be this request get IN RCP how to get RCp data in django -
Upgrading Django from 3.2 LTS to Django 5.04 causes typeerror: requires_system_checks must be a list or tuple
I just upgraded Django from 3.2 LTS to the latest Django 5.0.4 and updated all packages as on a need basis and I get the following trace after I attempt to run the docker-compose to start my api web server : my-api | File "/opt/my-api-core/manage.py", line 22, in <module> my-api | execute_from_command_line(sys.argv) my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line my-api | utility.execute() my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute my-api | self.fetch_command(subcommand).run_from_argv(self.argv) my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 275, in fetch_command my-api | klass = load_command_class(app_name, subcommand) my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 49, in load_command_class my-api | return module.Command() my-api | File "/usr/local/lib/python3.10/site-packages/django_media_fixtures/management/commands/collectmedia.py", line 35, in __init__ my-api | super(Command, self).__init__(*args, **kwargs) my-api | File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 285, in __init__ my-api | raise TypeError("requires_system_checks must be a list or tuple.") my-api | TypeError: requires_system_checks must be a list or tuple. The following is what I've attempted so far: The django-media-fixtures is what is seen in the trace so I used https://pypi.org/project/django-media-fixtures-next/ after changing it from https://pypi.org/project/django-media-fixtures/ Downgraded Django up until 4.2.11 and right up until 4.1 from the present 5.0.4 However , the error persists. I do not see the need to modify site-packages itself as it doesn't seem … -
How to redirect to homepage in Django if already logged in and then try to access /accounts/login/?
So I have "django.contrib.auth.urls" to implement login in my app called accounts. I also have set LOGIN_REDIRECT_URL = "home" LOGOUT_REDIRECT_URL = "home" in settings. When I log in it redirects me to the home page as I have set it up in a template below. The problem is when I am logged in and then try to go to /accounts/login/, it still redirects me to login page. I couldn't understand how to make it automatically redirect to homepage if user is authenticated and they try to access either 'accounts/login/' or 'accounts/signup/. I thought this behavior was included in "django.contrib.auth.urls". What do I get wrong? Here's my project.urls setup: from django.contrib import admin from django.views.generic.base import TemplateView from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='home.html'), name='home'), ] Here's my accounts.urls: from django.urls import path from accounts.views import SignUpView, log_out urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('logout/', log_out, name='logout'), ] These are my views: from django.urls import reverse_lazy from django.views.generic import CreateView from django.contrib.auth import logout from django.shortcuts import redirect from accounts.forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') … -
How to detect selected text from a PDF using Python in a Django application?
I have a Python script that successfully detects selected text from a PDF file using the xdotool and pyperclip libraries. Here's the script: import time import os import subprocess import pyperclip def get_selected_text(): subprocess.run(['xdotool', 'key', 'ctrl+c']) time.sleep(1) return pyperclip.paste() if __name__ == "__main__": pdf_filepath = 'class3english.pdf' subprocess.Popen(['xdg-open', pdf_filepath]) while True: selected_text = get_selected_text() if selected_text: print("Selected text:", selected_text) time.sleep(2) However, when I try to integrate this script into my Django application, it doesn't detect the selected text from the PDF. Instead, it captures text from the clipboard. I want to be able to detect text that the user has actively selected within the PDF viewer. Is there a way to achieve this within a Django application? How can I modify my approach to capture only the selected text from a PDF when running within a Django environment? -
Problem with Django form field styling upon error
I'm building my first website with Django and I have encountered what I think is a really weird problem. I have a form in the page, and I want that, if the user inputs invalid data in one of its fields, that field is marked with a specific CSS style. What I have done is write a validation method (a "clean()" method) that checks the input provided by the user. If it doesn't pass the validation, the class "error" is added to the widget of that input. Then, using CSS, I give that .error class some specific styling. Here is the problem: the error style is not applied correctly to the fields "name", "last name" and "email" of the form. For instance, when you input an invalid last name, both the field "last name" and "name" get highlighted in red, and when you input an invalid email address, both the "email" and the "name" fields get highlighted. I have gone over the "forms.py" file a thousand times and I can't figure out what's wrong. Here is the code of the "forms.py" file: from django import forms from .models import Appointment class AppointmentForm(forms.ModelForm): class Meta: model = Appointment fields = ['name', … -
client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable
{ "error": "Input nbnb.csv of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported." } if not self.origin_server or self.client_is_modern(): File "C:\Program Files (x86)\lib\wsgiref\handlers.py", line 358, in client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable tried spliting that code but still its not working -
Django / Websocket : How to get all actives `websockets`?
I would like get all websockets opened with a consumer like an .objects.all(). It is possible like this ? or with another method to "list" all actives websockets ? Thank you everyone in advance for answers ! I found nothing about that in the documentation or anything else, but if a thing like that exists, it can very useful.