Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: KeyError at /panel/home/login/ 'HTTP_REFERER'
I have a problem to get the HTTP_REFERER address from django. I want to userauth system in two separate login pages and for that, I set in one of login pages if the url that redirected person to this login page had 'business' word, redirect user into business login page. Thanks for Help I wrote this Code: if 'business' in request.META['HTTP_REFERER']: return redirect('panel_business:login_business') Here is My Error: KeyError at /panel/home/login/ 'HTTP_REFERER' Django Error Full Trace: Environment: Request Method: GET Request URL: http://localhost:8009/panel/home/login/?next=/panel/business/ Django Version: 4.2.6 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'panel', 'panel_business'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/arshia/w/recycle/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/arshia/w/recycle/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/arshia/w/recycle/panel/views.py", line 44, in login_home if 'business' in request.META['HTTP_REFERER']: Exception Type: KeyError at /panel/home/login/ Exception Value: 'HTTP_REFERER' -
Advice regarding integrating C# code with django backend
I use C# to convert documents (pdf, docx etc) to other formats (docx, xls, ppt etc) and my backend is written with Python (django) I successfully wrote and loaded a c# dll which let me call it's functions and convert the documents directly from python, using pythonnet clr Issue is, it's slow, like marginally slower (I'd say 20 times slower) than using the same code as if I compiled and ran it as an executable instead of loading it as a dll to python So I need an advice, should I just make the c# code into an executable and then call it via a subprocess with a file path argument (which will force me to write the file into the disk, call the subprocess, which will on turn read the file, and write again, and then the python will read the output file and delete it) or is there alternative? With the dll solution i just pass the file bytes to the dll and don't need to write a file to disk, which would be (for me) a preferable solution, but not at the cost of that big of speed diffrance. Im assuming passing the entire file's contents (bytes) … -
DRF Simple JWT functions RefreshToken.for_user(user) get Attribute error with Custom User Model
I create a custom User Model with usercode is PrimaryKey class User(AbstractBaseUser, PermissionsMixin): usercode = models.CharField(primary_key=True, unique=True, null=False) username = models.CharField(max_length=255, unique=True, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) phone_number = models.CharField(max_length=128, unique=False, null=True, blank=True, default=None) password = models.CharField(max_length=256, null=False) ... I replace default TokenObtainPairView serialier of SimpleJWT with and work quite good class CustomTokenObtainPairSerializer(serializers.Serializer): usercode = serializers.CharField(max_length=64) password = serializers.CharField(max_length=255) def validate(self, attrs): usercode = attrs['usercode'].upper() password = attrs['password'] # Get user object for validating user = User.objects.filter(usercode=usercode).first() # Validating login request if user is None: raise AuthenticationFailed(f'User not found!') if not check_password(password, user.password): return Response({'message': 'Wrong password!'}) user_data = UserSerializer(user).data tokens = get_tokens_for_user(user) return {'user': user_data, 'tokens': tokens} class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } But when I try to get custom token like source Creating tokens manually I got error at RefreshToken.for_user(user) Errors details: AttributeError at /application/api/v1/2024/token/ 'User' object has no attribute 'id' Request Method: POST Request URL: http://127.0.0.1:8000/application/api/v1/2024/token/ Django Version: 5.0.3 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'id' I checked and got that the RefreshToken.for_user require a User model with id is PrimaryKey File "D:\development\py\DJ_Project\venv\Lib\site-packages\rest_framework_simplejwt\tokens.py", line 203, in for_user user_id … -
Creating database in PostgreSQL following Django installation
Forgive me my indolence, but I was following Django installation based on this manual https://idroot.us/install-django-opensuse/ up until to the point where you need to create new database using createdb mydatabase. I am using OpenSuse Tumbleweed Release 20240320 and I have tried this in Python virtual environment. Now, It is giving an obvious error when using createdb mydatabase: "Connection to server on socket "/run/postgresql/.s.PGSQL.5432" failed: No such file or directory. Is the server running locally and accepting connections on that socket?" So I have checked the following: ps -ef | grep postgres It gives me this: root 12831 27003 0 11:18 pts/0 00:00:02 sudo su - postgres root 12833 12831 0 11:18 pts/1 00:00:00 sudo su - postgres root 12834 12833 0 11:18 pts/1 00:00:00 su - postgres postgres 12835 12834 0 11:18 pts/1 00:00:00 -bash postgres 12956 12835 0 11:21 pts/1 00:00:02 yes root 13133 12835 0 11:24 pts/1 00:00:00 sudo su - postgres root 13135 13133 0 11:24 pts/2 00:00:00 sudo su - postgres root 13136 13135 0 11:24 pts/2 00:00:00 su - postgres postgres 13137 13136 0 11:24 pts/2 00:00:00 -bash postgres 14851 13137 99 11:59 pts/2 00:00:00 ps -ef postgres 14852 13137 0 11:59 pts/2 00:00:00 grep … -
Django Load bootstrap modal only after form validation passes
Am trying to pop up a modal window with the terms & conditions, Only when the user accepts the terms and conditions then the data is submitted to the database. I want to validate user input before the modal pops up. Below is my code. individual_account.html <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" id="individualForm"> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field.errors }} {{ hidden_field }} {% endfor %} <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{form.full_name.id_for_label}}"> {{ form.full_name.label }} </label> {{ form.full_name }} {% if form.full_name.errors %} {% for error in form.full_name.errors %} <p class="text-red-600 text-sm italic pb-2">{{ error }}</p> {% endfor %} {% endif %} </div> <div class="w-full md:w-1/2 px-3"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{form.id_passport_no.id_for_label}}"> {{ form.id_passport_no.label}} </label> {{ form.id_passport_no }} {% if form.id_passport_no.errors %} {% for error in form.id_passport_no.errors %} <p class="text-red-600 text-sm italic pb-2">{{ error }}</p> {% endfor %} {% endif %} </div> </div> <!-- Button trigger modal --> <button type="button" class="bg-yellow-700 text-white rounded-none hover:bg-white hover:text-blue-900 hover:border-blue-900 shadow hover:shadow-lg py-2 px-4 border border-gray-900 hover:border-transparent" data-bs-toggle="modal" data-bs-target="#exampleModal"> Create Account </button> <!-- Modal --> <div class="modal fade" … -
Django Template render annotated data along with Model data in UI for Many to Many relationship objects
I am looking for a solution to show a Models data elements along with this annotated data, e.g. I have a TestRun model which has M2M relationship with TestCases, so on the UI page for testruns list page want to show TsetRun data along with the count of testcases grouped by its status. e.g. TestRun.ID = 1, TestRun.Name = Regression Total TCs in TR = 4 Passed TC = 2 | Blocked TC = 1 | Failed TC = 1 along with a table for each run record to show the above 4 testcases like TC_ID|TC_NAME|TC_STATUS| 1 |TC_101 | Passed | 4 |TC_102 | Passed | 5 |TC_105 | Failed | 7 |TC_107 | Blocked | I have following models class TestRun(models.Model): testcases = models.ManyToManyField(TestCase, through="TestRunCases") project = models.ForeignKey(Project, related_name="project_testruns", on_delete=models.PROTECT) name = models.CharField(max_length=255) class TestRunCases(models.Model): testcases = models.ForeignKey(TestCase, on_delete=models.CASCADE) testrun = models.ForeignKey(TestRun, on_delete=models.CASCADE) testcase_status = models.ForeignKey(TestCaseStatus, null=True, default=1, on_delete=models.PROTECT) I want to show the count of test cases for each run with status, e.g. For TestRun.id=1, Total TC#=3,Passed=2, Failed=1, template eg. provided below I tried using following in my views, using CBV def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["testcases"] = ( TestRunCases.objects.filter(testrun_id__in=testrun_qs) .values("testrun_id", "testcase_status__status_value") .annotate(status_count=Count("id")) ) return context And … -
Delete an instance before saving a new one (Django model save method)
I want to limit my model's records to a maximum of 10 rows per user (the model has a foreign key to user model). What is the best practice for that? I thought about overriding save method, perform a check, and delete before saving: def save(self, *args, **kwargs): if MyModel.objects.filter(user=self.user).count() >= 10: oldest_record = MyModel.objects.filter(user=self.user).order_by('created_at').first() oldest_record.delete() super().save(*args, **kwargs) But I wonder if it is a good solution, if it's better (and what's the way to do it) to enforce that at database level, and potential problems when same user saves two instances at the same time (though very unlikely). Any experiences with something similar? -
How to wait until the receive function is not invoked (set the client input in kc.input())?
I am trying to build a Python IDE using the Jupyter client kernel. My problem is: Not being able to provide the client input in the kc.input() that I receive after sending the prompt: : await self.send(text_data=json.dumps({'input_request':mseg["content"]["prompt"]})) need help here if msg["msg_type"] == "execute_input": mseg = kc.get_stdin_msg(timeout=1) await self.send(text_data=json.dumps({'input_request': mseg["content"]["prompt"]})) ***I want it to wait until it doesn't receive input (invoke the receive function)*** print("Stored input:", self.input_received) kc.input(5) I try to declare the kc = BlockingKernelClient() in the class so can use in if i received any input but kernel get stop till then. Full Code import json from channels.generic.websocket import AsyncWebsocketConsumer from jupyter_client import BlockingKernelClient from jupyter_client import KernelManager class CodeExecutionConsumer(AsyncWebsocketConsumer): input_received = '' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): await super().receive(text_data) data = json.loads(text_data) code = data.get('code', '') input_text = data.get('input','') if input_text: print("input text:",input_text) await self.handle_input(input_text) else: result = await self.execute_code(code) print(code,result) # await self.send(text_data=json.dumps({'result': result})) async def handle_input(self, input_text): print("Received input:", input_text) self.input_received = input_text async def execute_code(self, code): kc = BlockingKernelClient() kc.load_connection_file(connection_file="./confs/c1.json") kc.start_channels() try: msg_id = kc.execute(code) while True: msg = kc.get_iopub_msg(timeout=1) if msg["msg_type"] == "stream" and msg["content"]["name"] == "stdout": result … -
Improving Django Application Performance: Comparing Blocking and Non-blocking Implementations
I encountered an unexpected error (apr_socket_recv: Connection reset by peer (54)) while load testing my Django application with Apache Benchmark (ab). This error occurs when I increase the load to 50 concurrent requests. Surprisingly, even with 20 concurrent requests, there's no significant performance improvement with non-blocking (Can see same throughput as of blocking) The application consists of two implementations: one using a blocking approach with the default WSGI server and the other utilizing a non-blocking asynchronous approach with ASGI and the Daphne server. The blocking implementation relies on synchronous requests with the requests library, while the non-blocking approach utilizes aiohttp within an asynchronous view function. Both implementations aim to make POST requests to an external API endpoint and return responses. Despite expecting better performance with the asynchronous approach, the error persists and the performance remains stagnant. I'm seeking insights into the root cause of this error and potential solutions to improve performance under heavier loads. Additionally, any advice on optimizing the asynchronous implementation or suggestions for better load-testing strategies would be greatly appreciated I'm using ab as a benchmarking tool. The command which I used for benchmarking: ab -c 50 -n 600 -s 800007 -T application/json "http://127.0.0.1:8001/test" Blocking Code: from … -
Spinner and page reset after views.py completes processing | DJANGO
I have a Django web application where users can generate and download Excel files. To provide feedback to users while the file is being generated, I've implemented a spinner animation using HTML and JavaScript. However, I'm facing difficulty in stopping the spinner animation after the file download is complete. Here's my HTML and JavaScript code for the spinner: <style> .spinner-container { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 9999; } .spinner { width: 50px; height: 50px; border: 5px solid rgba(0, 0, 0, 0.1); border-left-color: #333; border-radius: 50%; animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } </style> <button type="submit" onclick="showSpinner()">GENERATE</button> <div id="spinner" class="spinner-container"> <div class="spinner"></div> </div> <script> function showSpinner() { document.getElementById("spinner").style.display = "block"; } function hideSpinner() { document.getElementById("spinner").style.display = "none"; } </script> And here's my Django views.py code for downloading the file: from django.http import HttpResponse import pandas as pd def downloadFile(request): try: # Generate the Excel file with pd.ExcelWriter('NEW-DOWNLOAD.xlsx', engine='openpyxl') as excel_file_path: # Write dataframes to sheets dataframes = { 'SUMMARY': data, 'CHART': CHART } for sheet_name, df in dataframes.items(): df.to_excel(excel_file_path, sheet_name=sheet_name, index=True) # Read the entire file as bytes with open('NEW-DOWNLOAD.xlsx', 'rb') as f: file_data = f.read() … -
no_color in overridden django command does not work
I have overridden django check command in ~/<project_name>/commands/management/commands/check.py looking like this: from django.core.management.commands import check class Command(check.Command): help = 'My Customized Version of the Original check Command' def handle(self, *args, **options): print('>>> Running customized check') options['deploy'] = True options['no_color'] = True super(Command, self).handle(*args, **options) Running manage.py check 2>/tmp/check-output triggers the command, but the problem here is in spite of setting 'no_color', the output is still colored and I have to run it as manage.py check --no-color 2>/tmp/check-output -
Django (REST) backend server hosting using Google Cloud
This is my first time trying to host a backend server to any cloud platform and I am trying to host it using Google Cloud. This is a pet project of mine and the frontend of my webapp is alreday hosted by myself using firebase. My issue is I tried depolying the cloud app for my backend, but I am getting a 500 server error even though the files were uploaded without any issues. Another thing is I am quiet not sure about my file structure. [Backend File Strucutre](https://i.stack.imgur.com/PLAtJ.png) [API folder](https://i.stack.imgur.com/AGGKQ.png) [enchant_ease_backend File](https://i.stack.imgur.com/AQ4hH.png) [My backend folder](https://github.com/ThisalHerath/express-hello-world) I tried removing my requirements.txt file since in the Google cloud app engine dashboard I got few errors with my dependencies but id did not worked out and I spent almsot few hours watching tutorials but nothing worked out. Can someone guide me through the hosting process or tell me what i have done wrong or something that need to be changed? -
Django data is not being stored on Postgres Db
Up until January, my Django app was saving data to this DB but now it is not working. The migrations pass and declare ok on the CLI but it doesn't get saved in the DB. It still works with SQLite3 DB but I get this error { "error": "'NoneType' object has no attribute 'rsplit'" } I did not make any big change to the settings prior to this -
in Django i'm trying to rendering a list of objects from a different models in a class based detail view
I have two models Vendors and Products. Products has a foreign key of vendors. What I'm trying to do is when you go to a detail view of vendor it shows then vendor model information then a list of Products from that vendor. I currently just testing flow and getting to know django so a lot this code is very generic and i know i need to clean it up. Here is my models class Vendor(models.Model): name = models.CharField(max_length=126, unique=True, blank=True, null=True) contact_number = models.CharField(max_length=126, blank=True, null=True) address = models.CharField(max_length=126, blank=True, null=True) email = models.EmailField(max_length=126, blank=True, null=True) is_active = models.BooleanField(default=True) def __str__(self): return self.name def productFilepath(instance, filename): year = datetime.now().strftime("%Y/") return os.path.join(instance.vendors.name, year, filename) class Product(models.Model): vendors = models.ForeignKey(Vendor, on_delete=models.CASCADE) collection = models.CharField(max_length=126, unique=True, blank=True, null=True) product = models.CharField(max_length=126, blank=True, null=True) size = models.CharField(max_length=126, blank=True, null=True) vendor_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) retail_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) sku = models.CharField(max_length=126, unique=True, blank=True, null=True) year = models.PositiveSmallIntegerField(blank=True, null=True) quarters_in_year = { 'q1': 'Q1', 'q2': 'Q2', 'q3': 'Q3', 'q4': 'Q4', } quarter = models.CharField(max_length=2, choices=quarters_in_year.items(), blank=True, null=True) image = models.FileField(upload_to=productFilepath, blank=True, null=True) here are my views class VendorDetailView(DetailView): model = Vendor template_name = 'deliveries/vendor_detail.html' class Productlist(ListView): model = Product template_name = … -
How to couple Django connection.cursor() with rest_framework generics?
Working on a project where we want to bypass Django ORM and use direct SQL queries instead. We will have lots of simple APIs, hence wanted to use rest_framework generics view classes. But querysets implemented via connection.cursor() don't update when data changes. I.e. if a POST is made to a generics.ListCreateAPIView, the new data gets saved to the DB, but consecutive GET requests still show the dataset as it was before the POST. MODELS: from django.db import models class identifier_type(models.Model): type_name = models.CharField(max_length=25, unique=True) SERIALIZERS: from rest_framework import serializers from .models import * class IdentifierTypeSerializer (serializers.ModelSerializer): class Meta: model = identifier_type fields = ['id', 'type_name'] VIEWS: from rest_framework import generics from .models import identifier_type from .serializers import IdentifierTypeSerializer from .queries import identifier_type_select_all from .utils import dict_fetch_all class IdentifierTypesCR(generics.ListCreateAPIView): queryset = dict_fetch_all(identifier_type_select_all) # does not update GET after PUT # queryset = identifier_type.objects.all() # alternative- Django ORM updates GET after PUT serializer_class = IdentifierTypeSerializer UTILS: from django.db import connection def dict_fetch_all(query, *args): cursor = connection.cursor() cursor.execute(query, *args) desc = cursor.description rows = cursor.fetchall() if rows: return [dict(zip([col[0] for col in desc], row)) for row in rows] else: return None QUERIES: identifier_type_select_all = "SELECT * FROM staticdata_identifier_type" URLS: from django.urls import path … -
Django how do I use system timezone?
For whatever reason, django is defaulting to use America/Chicago when TIME_ZONE is not specified. My server runs in local devices, so the system timezones is all over the place and could change if people move around. Is there a way to accomplish this? I just want os.environ["TZ"] to not be set, is this possible? Django on startup will set it to that variable to chicago -
Our website was deployed on heroku, and now we are developing our mobile app on flutter using the same heroku db, what should I do?
Our website was deployed on heroku, and now we are developing our mobile app on flutter using the same heroku db, what should I do? We want the website and the app to share the same database. Should I just add api endpoint to the original framework? I am just so confused -
How to change the value of a field when the user clicked the notification button
I am developing a notification system in Django where users receive notifications when someone comments on an article they posted in the app. However, I am encountering an issue where I cannot modify the value of a field in the notification model when a user clicks a notification button in the template. Let me provide an example: When I ask a question on Stack Overflow and someone comments on the question, I receive a notification stating that someone has commented on my question. When I click the URL in the template, the red badge disappears, indicating that the author of the question has already read the comment on that question. This is precisely the functionality I am aiming to achieve here. However, using the current method in my views.py file, the method returns an error stating: 'int' object has no attribute 'is_read'. def all_article(request): articles = Article.objects.all() notifications = Notification.objects.filter(user=request.user) unread_notifications = Notification.objects.filter(user=request.user, is_read=False).count() if unread_notifications.is_read == False: unread_notifications.is_read == True unread_notifications.save() return render(request, 'article.html', {"articles":articles, "notifications":notifications, "unread_notifications":unread_notifications}) models.py: class Notification(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) message = models.TextField() link = models.URLField(unique=True) is_read = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) template: <nav class="navbar navbar-light bg-light shadow-sm bg-body"> <div class="container"> … -
Can't render views of html in django
My models from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): USER_TYPE_CHOICES = ( ('user_type1', 'User Type 1'), ('user_type2', 'User Type 2'), ) user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES) groups = models.ManyToManyField( 'auth.Group', related_name='customusers', # Override the default related name ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='customusers_permissions', # Specify a related name for custom user permissions ) My views.py: from django.shortcuts import render, redirect from .forms import CustomUserCreationForm # Assuming you have a CustomUserCreationForm def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() # Redirect to a success page or another page return redirect('success') # Replace 'success' with the URL name of your success page else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}) My html trample: <meta charset="UTF-8"> <title>User Registration</title> <h1>Register</h1> {% if form.errors %} <p style="color: red;">There are errors in your form.</p> <ul> {% for field, errors in form.errors.items %} {% for error in errors %} <li>{{ field }}: {{ error }}</li> {% endfor %} {% endfor %} </ul> {% endif %} <form method="post"> {% csrf_token %} <label for="username">Username:</label> {{ form.username }}<br> <label for="email">Email:</label> {{ form.email }}<br> <label for="password">Password:</label> {{ form.password }}<br> <label for="user_type">User Type:</label> <select name="user_type" id="user_type"> {% for choice in form.user_type.field.choices %} <option value="{{ choice.0 … -
Deployment of nginx with django on port 80 and node.js in port 3001
I am using the following github repository https://github.com/sebaburella/Api-Whatsapp and i want to use the funcionality of this in a django proyect but I dont know nothing about node This github repository it supposedly works as an alternative of the oficial whatsapp api. My nginx configuration is the following froma this tutorial https://tonyteaches.tech/django-nginx-uwsgi-tutorial/ upstream django { server unix:///home/udoms/microdomains/microdomains.sock; } # configuration of the server server { listen 80; server_name micro.domains www.micro.domains; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/udoms/microdomains/media; } location /static { alias /home/udoms/microdomains/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/udoms/microdomains/uwsgi_params; } } -
meson-python: error: Could not find ninja version 1.8.2 or newer while installing pandas
I am deploying my Django app on shared hosting via name cheap. I am using cPanel shell terminal. I have some dependencies on requirements.txt file. I am installing it via terminal session but unable to install numpy or pandas it shows the following error. So the problem here is I already have installed the ninja version 1.11.1 and required is 1.8.2 or newer so basically it is not detecting the ninja. I also have downgraded the ninja version and tried different combinations but nothing works. Any help will be appriciated. ((app:3.11)) [abc@server123 simply]$ pip install pandas Collecting pandas Using cached pandas-2.2.1.tar.gz (4.4 MB) Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> [35 lines of output] Collecting meson-python==0.13.1 Using cached meson_python-0.13.1-py3-none-any.whl.metadata (4.1 kB) Collecting meson==1.2.1 Using cached meson-1.2.1-py3-none-any.whl.metadata (1.7 kB) Collecting wheel Using cached wheel-0.43.0-py3-none-any.whl.metadata (2.2 kB) Collecting Cython==3.0.5 Using cached Cython-3.0.5-py2.py3-none-any.whl.metadata (3.2 kB) Collecting numpy<=2.0.0.dev0,>1.22.4 Using cached numpy-1.26.4.tar.gz (15.8 MB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Installing backend dependencies: started Installing backend dependencies: finished with … -
Javascript does not redirect and time is stay same in Django Application. How to solve it?
Hi everyone I try to build web application with using django and js. It is kind of chat application there are rooms and each room have time after time is up. I want to delete room. While I making test, I realize if one user in room,other user in list page, room does not delete when 1 user in room and other list page. Time is stay 1 seconds How can ı solve this problem. Can you help me? Thank You. room_detail_page function updateRemainingTime() { // Sunucuya AJAX isteği gönder var xhr = new XMLHttpRequest(); xhr.open('GET', '/remaining-time/' + roomName + '/', true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var remainingTime = JSON.parse(xhr.responseText); // Kalan süreyi güncelle document.getElementById('remaining-time').textContent = remainingTime.minutes + ':' + remainingTime.seconds; if (remainingTime.minutes <= 0 && remainingTime.seconds <= 0) { deleteRoom(roomName); } } }; xhr.send(); } function deleteRoom(roomId) { var xhr = new XMLHttpRequest(); xhr.open('POST', '/delete-room/' + roomId + '/', true); xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}'); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { window.location.href = '/home'; location.reload() } }; xhr.send(); } setInterval(updateRemainingTime, 1000); room_list_page function updateRemainingTime(roomId) { // Sunucuya AJAX isteği gönder var xhr … -
why set password method doesn't working in django?
I implemented the user manager class but my set_password method only works for super users and I have problem with regular users log in this is my manager.py: from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, username, phone_number, password, **extra_fields): if not phone_number: raise ValueError('Phone number must be set!') user = self.model(username=username, phone_number=phone_number, **extra_fields) user.set_password(user.password) user.save(using=self._db) return user def create_superuser(self, username, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, phone_number, password, **extra_fields) this is my user model: from django.db import models # Create your models here. from django.core.validators import RegexValidator from django.db import models from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import AbstractUser from .manager import UserManager `class User(AbstractUser): GENDER_CHOICE = ( ('he', 'male'), ('she', 'female') ) HOBBIES = ( ('sport', '🏆'), ('music', '♫'), ('movie', '🎬'), ('sleeping', 'ᶻ 𝗓 𐰁'), ('photography', '📷') ) username = models.CharField(max_length=25, unique=True) phone_number = models.CharField(max_length=11, validators=[RegexValidator( regex=r"^09[0|1|2|3][0-9]{8}$" )]) biography = models.CharField(max_length=20, default=None, null=True, blank=True) hobbies = models.CharField(choices=HOBBIES,max_length=250,null=True,blank=True) gender = models.CharField(choices=GENDER_CHOICE, max_length=250, null=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['phone_number', 'password'] objects = UserManager()` I've tried set_password mthod in my manager file but it only works for super users and it doesn't hash regular users's password and i have problem with log in for regular users because … -
Django form not submiting to server
When I create a new user account I set the terminal to print working if the create account form works and the terminal does that but the created accounted doesn't show on django admin panel which means the account wasn't created and since the account wasn't created I don't get redirected to create profile page my views.py from django.shortcuts import redirect, render from django.contrib.auth.models import User, auth from django.http import HttpResponse from django.contrib import messages from .models import UserProfile from .forms import UserRegistrationForm, UserProfileForm from django.contrib.auth import login from django.http import JsonResponse from .models import Posts from .models import Videos # Create your views here. def home(request): post = Posts.objects.all() video = Videos.objects.all() return render(request,'Index.html',{'Home':'Title', 'Posts':post, 'Videos':video,}) def createAccount(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) profile_form = UserProfileForm(request.POST, request.FILES) if user_form.is_valid() and profile_form.is_valid(): username = user_form.cleaned_data['username'] email = user_form.cleaned_data['email'] password = user_form.cleaned_data['password'] password2 = user_form.cleaned_data['password2'] # Add this line if password != password2: # Check if passwords match user_form.add_error('password2', 'Passwords do not match') # Add error message elif User.objects.filter(username=username).exists(): user_form.add_error('username', 'This username is already taken.') elif User.objects.filter(email=email).exists(): user_form.add_error('email', 'This email is already registered.') else: user = user_form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() login(request, user) messages.success(request, 'Your account … -
Problem in importing model files from same module
Below is the pic of my Django Project structure. Django Structure I am trying to import model in data_models folder but it saying no module found. I have attached the pic for reference. Please guide me. Error Image I have tried many thing like removing it from main directory but still not working fine.