Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Meta Package for other Language
I have several questions about Meta package (for Meta tags in templates) of Django and those are : 1.Does this package can support other languages like Persian? 2.If it can support, I just need to change my Language_Code to "fa-IR", or should I consider this answer too? Thanks for your attention. -
Django Forms widget tweaks allow only alphatbet letters in text field
I am trying to restrict input in text fields to only alpha letters also via client side I have tried this, but this doesn't work. the script: <script type="text/javascript"> function Validate(e) { var keyCode = e.keyCode || e.which; var regex = /^[A-Za-z]+$/; var isValid = regex.test(String.fromCharCode(keyCode)); return isValid; } </script> Then the call: {% render_field form_built_properties.building_material|attr:"onkeypress(Validate)" class="form-control" %} I tried this alone, doesn't work either: {% render_field form_built_properties.building_material|attr:'onkeydown="return /[a-z]/i.test(event.key)"' Ideally there should be a function that on clicking the submit button checks that building_material text field (and others) have been correctly filled before submitting all data. -
CSS not connecting in Django
Page not found (404) 'css\static.css' could not be found Request Method: GET Request URL: http://127.0.0.1:8000/static/css/static.css Raised by: django.views.static.serve urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py: """ from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'pushkin.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pushkin.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = '/static/' STATIC_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/css'), ] STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> … -
unable to prepare context: path "/Users/ahmetcankoca/Desktop/learning Django/resume/nginx" not found
I created an ngnix folder in the project to run it in docker and get my site up, but it doesn't work, it says ngnix not found and shows the absolute path. I'm trying to get my site up and running, it's not something I know very well about, I'm looking forward to your help. -
400 Bad Request: Djoser built-in create user using django Signals
I have 3 models (including Custom User) structured: accounts.models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models #type: ignore from django.utils.translation import gettext_lazy as _ from django.utils import timezone from phonenumber_field.modelfields import PhoneNumberField #type: ignore # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, email, user_role, password=None, **extra_fields): if not email: raise ValueError("Users must have an email address.") if not user_role: raise ValueError("Users must have a user role.") email = self.normalize_email(email) user = self.model(email=email, user_role=user_role, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, user_role="admin", password=None, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_admin", True) extra_fields.setdefault("is_active", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("Superuser must have is_staff=True.")) if extra_fields.get("is_admin") is not True: raise ValueError(_("Superuser must have is_admin=True.")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("Superuser must have is_superuser=True.")) return self.create_user(email, user_role, password, **extra_fields) class UserAccount(AbstractBaseUser, PermissionsMixin): USER_ROLES = ( ("resident", "Resident"), ("healthworker", "Health Worker"), ("admin", "Admin") ) email = models.EmailField(_("email address"), unique=True) user_role = models.CharField(max_length=100, choices=USER_ROLES) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["user_role",] objects = UserAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def save(self, *args, **kwargs): if self.user_role == "admin": self.is_staff = … -
Mismatch between column type in MySQL and Django model value
I have a model class defined as follows: class Person(models.Model): # ... spending = models.BigIntegerField(blank=True, null=True) # ... And populate it like so: p = Person( # ... spending = str(row['spending']) # ... ) p.save() In which row is a pandas DataFrame row. What will the type of the field be in the database? What if the field is defined as TextField and what I insert is int(row['spending')? Looking at the type in MySQL I can guess the defined field type is enforced. Will it still be the case if the column contains null values? For example, the field is of type numeric and we insert null values will it remain numeric or it will change to Text to accomodate the nulls? -
How do I stop http automatically going to https?
When redirecting from a home page to another page I continuously get "You're accessing the development server over HTTPS, but it only supports HTTP." Out of the two buttons that redirect only one provides this issue, and the other redirects fine. Code in vscode Browser error I've tried setting SECURE_SSL_REDIRECT to false in settings.py however I still get this error. -
Slow Loading and 500 Errors with Django Project on Apache Server
Hello Stack Overflow community, I'm encountering performance issues with my Django project hosted on an Apache server. When accessing the site through Apache, it either takes a very long time to load or returns a 500 error. However, when I use Django's runserver command and access the site through a tunnel, it loads fine without any issues. Could someone help me understand why my Django project is slow or failing when hosted on Apache, but works well with runserver? (it's my first time tried to hosted an project) here's my configfile: <VirtualHost *:80> ServerAdmin admin@taicles.com ServerName taicles.com ServerAlias www.taicles.com Alias /static /home/sami/SerurierProject/static <Directory /home/sami/SerurierProject/static> Require all granted </Directory> <Directory /home/sami/SerurierProject/SerurierProject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess SerurierProject python-path=/home/sami/SerurierProject:/home/sami/venv/lib/python3.10/site-packages WSGIProcessGroup SerurierProject WSGIScriptAlias / /home/sami/SerurierProject/SerurierProject/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> -
Celery Emails and Accessing Mailbox
I'm in the process of moving my emails over to Celery tasks to run asychronously. Porting over my existing tests I'm struggling with an AssertionError when I attempt to access the mail.outbox. I assume this is due to the mailbox being created within the Celery thread rather than within the scope of the test. Is there any way around this to test the email has succesfully sent? I've pretty much ran out of ideas on the best way to approach this. Task from celery import shared_task from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from django.conf import settings from smtplib import SMTPException CONFIRMATION_MESSAGE = 'Thank you! Your enquiry has been received and one of our team will be in touch shortly.' @shared_task def send_contact_email(recipient, subject): try: #send a confirmation email email_content = render_to_string('base_email.html', {'message': 'message'}) # Create an EmailMultiAlternatives object email = EmailMultiAlternatives( subject=subject, body=CONFIRMATION_MESSAGE, from_email=settings.DEFAULT_FROM_EMAIL, to=[recipient] ) # Attach the HTML content to the email email.attach_alternative(email_content, "text/html") # Send the email email.send() except SMTPException as e: # Handle any SMTP exceptions print(f"SMTPException occurred: {str(e)}") except Exception as e: # Handle any other exceptions print(f"Exception occurred: {str(e)}") Test from django.conf import settings from django.test import TestCase, override_settings from django.core import … -
hyperlink leads to 404 error message, No Post matches the given query, Expecting to lead to `views.PostList.as_view()`
Expecting hyperlink in index.html to lead to views.PostList.as_view() hyperlink located in templates/base.html line 46: <a class="nav-link" href="{% url 'questions' %}">Top Questions</a> Leads to http://localhost:8000/questions/ as expected but with this error message: Page not found (404) No Post matches the given query. Request Method: GET Request URL: http://localhost:8000/questions/ Raised by: blog.views.PostDetail Using the URLconf defined in classroommatrix.urls, Django tried these URL patterns, in this order: admin/ index/ [name='index'] <slug:slug>/ [name='post_detail'] The current path, questions/, matched the last one. debugging steps taken So far I've reviewed urlpatterns and views.py as indicated by the error message. 1: review urlpatterns The problem seems to arise in the urlpatterns in blog/urls.py. The error message indicates that views.PostDetail.as_view() is problematic: # blog/urls.py (called through classroommatrix/urls.py) from . import views from django.urls import path urlpatterns = [ # url patterns for the blog app here. path('index/', views.PostList.as_view(), name='index'), # home page path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), # post detail page - !!The error message indicates that PostDetail is problematic: path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'), # post like path('questions/', views.PostList.as_view(), name='questions'), # questions page ] 2: review PostDetail Seems a less likely problem area as there is no mention of 'questions/' in `PostDetail class. # blog/views.py from django.shortcuts import render, get_object_or_404, reverse … -
what is the solution to this pip ERROR: Could not install packages due to an OSError: Could not find a suitable TLS CA certificate bundle
So I was trying my hand on a django project that has to do with authentication, on trying to install django-ses for aws email service, I have this error ERROR: Could not install packages due to an OSError: Could not find a suitable TLS CA certificate bundle, invalid path: C:\Program Files\PostgreSQL\16\ssl\certs\ca-bundle.crt and since I had installed postgressql 16/pgadmin for database. And now I discovered that it has affected my pip, I can't install any package, the error keeps popping up, please I need solutions to this, since I got a project deadline. I have tried various suggesions from this links: text text and various others, none is working, even youtube is not giving a solution. I need solution, any help will be appreciated. -
i am getting an error on fetching data from api in json format
enter image description here above image contains the django code as above code is providing 403 error ,i have used this api https://data.sec.gov/api/xbrl/companyfacts/CIK0001544522.json to fetch the data in json format but my django server is providing an 403 error ,kindly go through the image to see the code here is the postman response enter image description here -
Are ENV Variables also passed as a part of HTTP request?
I was experimenting with Django middlewares. And I happened to randomly print out request.META, I saw that my Environment variables are also passed on to the django server. My middleware.py class AnalyticsMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): for key in request.META: print(key, ": ", request.META[key]) return None Can someone explain what is happening? -
Django NoReverseMatch Error for 'questions' View After Google OAuth Sign-In
I'm working on a Django project with Google OAuth implemented. The homepage (index.html) loads correctly, and the Google OAuth sign-in functions as expected. However, I'm encountering a NoReverseMatch error when trying to redirect to the questions view after sign-in. Error Message: NoReverseMatch at / Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name. ... NoReverseMatch at / Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name. Request Method: GET Request URL: http://8000-lmcrean-classroommatrix-zp6cz7sdhxw.ws-eu106.gitpod.io/ Django Version: 3.2.23 Exception Type: NoReverseMatch Exception Value: Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name. Exception Location: /workspace/.pip-modules/lib/python3.9/site-packages/django/urls/resolvers.py, line 698, in _reverse_with_prefix Python Executable: /home/gitpod/.pyenv/versions/3.9.17/bin/python3 Python Version: 3.9.17 [...] Error during template rendering In template /workspace/Classroom-Matrix/templates/base.html, error at line 45 Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name. [...] 45 <a class="nav-link" href="{% url 'questions' %}">Top Questions</a> debugging steps below I have reviewed the problem areas and tried solving adjustments. templates/base.html same error message appears when changing 'questions' to 'index' in line 45. to Top Questions - leads to " 'index' is not a valid view function or pattern name." does … -
Passing data to modal from button
I want to make a post request to my django view with query params. The query params are coming from the html template. On accept button in template, a modal opens. And there is an accept button in the modal. I want to pass the data from button to the modal and then onclick of modal button, it will make an ajax call to the view. But I am not able to pass the values from button to the modal. Here is my code: Button part of the template:(The values {{ supervisor.supervisor.user.id }} and {{ supervisor.supervisor.user.id }} are accessible here.) {% for supervisor in proposal.supervisors %} <tr> <td> {% if supervisor.committee_status == 0 %} <span class="badge badge-warning text-dark">Pending</span> {% elif supervisor.committee_status == 1 %} <span class="badge badge-success text-success">Accepted</span> {% elif supervisor.committee_status == 2 %} <span class="badge badge-danger text-danger">Rejected</span> {% elif supervisor.committee_status == 3 %} <a href = "{% url 'proposal_modification' proposal.proposal.id supervisor.supervisor.user.id%}"> <span class="badge badge-info text-info " style="text-decoration: underline;"> Modifications</span> {% endif %} <div class="btn-group" role="group"> <button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#acceptModal" data-supervisor-id="{{ supervisor.supervisor.user.id }}" data-proposal-id="{{ proposal.proposal.id }}">Accept</button> <button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#rejectModal" data-supervisor-id="{{ supervisor.supervisor.user.id }}" data-proposal-id="{{ proposal.proposal.id }}">Reject</button> </div> </td> </tr> {% endfor %} Modal : … -
I am getting the error while connecting django to mongodb database using djongo
I am trying to create dynamic website using Django.For dynamic data i have tried to use mongodb Database.For the connection between mongo db and django ,djongo is used here. After defining the database and tried to the command makemigrations it shows the error. Data definition in Settings file.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'Cake_Bakery', 'CLIENT':{'host':'localhost','port':27017} } } error is given below: (cake) PS D:\Cake Eccomerce\cake\Cake_Bakery> python manage.py makemigrations System check identified some issues: WARNINGS: ?: (urls.W002) Your URL pattern '/products' [name='products'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. No changes detected Traceback (most recent call last): File "D:\Cake Eccomerce\cake\Cake_Bakery\manage.py", line 22, in <module> main() File "D:\Cake Eccomerce\cake\Cake_Bakery\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Cake Eccomerce\cake\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Cake Eccomerce\cake\Lib\site-packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Cake Eccomerce\cake\Lib\site-packages\django\core\management\base.py", line 415, in run_from_argv connections.close_all() File "D:\Cake Eccomerce\cake\Lib\site-packages\django\utils\connection.py", line 85, in close_all conn.close() File "D:\Cake Eccomerce\cake\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\Cake Eccomerce\cake\Lib\site-packages\django\db\backends\base\base.py", line 358, in close self._close() File "D:\Cake Eccomerce\cake\Lib\site-packages\djongo\base.py", line 208, in _close if self.connection: File "D:\Cake … -
getting error TypeError at /login/ ChatroomMiddleware.__call__() missing 2 required positional arguments: 'receive' and 'send'
i am trying to create a middleware for my chatroom/consumer so that i can access current logged-in user object in my consumer.py, but getting a error "getting error TypeError at /login/ ChatroomMiddleware._call_() missing 2 required positional arguments: 'receive' and 'send'" chatroom/consumer.py ( chatroom is app of my project) import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from chatroom.views import get_user_exist class GlobalChatConsumer(AsyncWebsocketConsumer): roomID = "global_room" sender = None message = "" async def connect(self): self.sender = self.scope["user"] print("USER ----> $", self.sender) await self.channel_layer.group_add(self.roomID, self.channel_name) await self.accept() messages = await self.retrieve_room_messages() async for message in messages: sender_username = await database_sync_to_async(lambda: message.sender.username)() await self.send( text_data=json.dumps( { "type": "chat_message", "message": message.content, "sender": sender_username, } ) ) async def disconnect(self, close_code): await self.channel_layer.group_discard(self.roomID, self.channel_name) async def receive(self, text_data): text_data_json = json.loads(text_data) message_type = text_data_json.get("type") self.message = text_data_json.get("message") print("Message type", message_type) print("Message -> ", self.message) if message_type == "join_room": self.roomID = text_data_json.get("roomID") await self.channel_layer.group_add(self.roomID, self.channel_name) await self.send( text_data=json.dumps( {"type": "info", "message": f"You have joined room {self.roomID}"} ) ) elif message_type == "chat_message": await self.save_chat_db() await self.channel_layer.group_send( self.roomID, { "type": "chat_message", "message": self.message, "sender": self.scope.get("user").username, }, ) async def chat_message(self, event): message = event["message"] sender = event["sender"] await self.send( text_data=json.dumps( { "type": "chat_message", "message": … -
Django API attribute not found
I am building an API using django and the django rest framework that uses models from tensorflow and scikit-learn. I have ran into an error where my CountVectorizer that I fitted and used in another python script and used pickle to export and import into my django project, raises an attribute error when I try to make a call to the API View. This is the error: Traceback (most recent call last): File "/home/dude/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/dude/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dude/.local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/home/dude/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/home/dude/Desktop/Projects/Finance Webapp/Financial_Chatbot_API/chatbot/views.py", line 36, in chatbotRequestHandler chatbotObj = ChatBot() File "/home/dude/Desktop/Projects/Finance Webapp/Financial_Chatbot_API/chatbot/functions.py", line 100, in __init__ AttributeError: Can't get attribute 'custom_preprocessor' on <module '__main__' from '/home/dude/Desktop/Projects/Finance Webapp/Financial_Chatbot_API/manage.py'> [25/Nov/2023 00:23:44] "POST / HTTP/1.1" 500 96891 This is my api view: @api_view(['POST']) data = request.data chatbotPrompt … -
How can I patch a celery task
I'd like to know how I can write unit tests to test a celery task correctly. Unfortunately, the internet gives testing examples of very simple celery tasks. My case looks as follows: I have a custom admin command which is a celery task that does 3 things: Makes a xlsx file from DB data, Uploads the xlsx file to s3, Send a link to the file to the request user (admin). I'd like to test 2 assertions: to test the file itself (that the xlsx file has correct DB data). But I don't understand how I can read the file which is created in the celery task to compare what the file has against the data in the DB. to test that the link is sent to the admin correctly. (I can do it in my second attempt) The code looks like this: Admin site: @admin.register(MyModal) class MyModelAdmin(admin.ModelAdmin): def export_xlsx(self, request, queryset): my_celery_task.delay(ids, queryset, request.user) actions = [export_xlsx] Celery task: @app.task(ignore_result=True) def my_celery_task(ids, queryset, user): # 1) makes a xlsx wb = openpyxl.Workbook() ws = wb.active # blablah wb.save(filename='/tmp/temp.xlsx') # 2) uploads to s3 s3 = boto3.resource('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, endpoint_url=settings.AWS_S3_ENDPOINT_URL) s3.Bucket(settings.AWS_STORAGE_BUCKET_NAME).upload_file('/tmp/temp.xlsx', 'file.xlsx') # 3) sends a link to the admin … -
How to customize the text for django humanize - naturaltime?
I'm using django humanize with the "naturaltime" template filter in my templates Right now it returns future dates as: "3 days from now" I'd like to customize it into something like "in 3 d" (so also changing the order of the words in the output) How would I go about doing that? -
Getting "OutstandingToken.user" must be a "User" instance
I am creating a register method using djangorestframework-simplejwt. I created a custom user in auth using AbstractBaseUser. This is my views.py: class GoogleSocialAuthView(GenericAPIView): serializer_class = GoogleSocialAuthSerializer def post(self, request): """ POST with "auth_token" Send an idtoken as from google to get user information """ serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) data = ((serializer.validated_data)['auth_token']) return Response(data, status=status.HTTP_200_OK) serializers.py class GoogleSocialAuthSerializer(serializers.Serializer): auth_token = serializers.CharField() def validate_auth_token(self, auth_token): user_data = google.Google.validate(auth_token) print("login status", user_data) #try: user_data['sub'] #except: #raise serializers.ValidationError( #'The token is invalid or expired. Please login again.' #) if user_data['aud'] != os.environ.get('GOOGLE_CLIENT_ID'): raise AuthenticationFailed('oops, who are you?') user_id = user_data['sub'] email = user_data['email'] name = user_data['name'] provider = 'google' return register_social_user( provider=provider, user_id=user_id, email=email, name=name) My custom user model: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) groups = models.ManyToManyField( Group, verbose_name='groups', blank=True, help_text= 'The groups this user belongs to. A user will get all permissions ' 'granted to each of their groups.' , related_name="my_auth_user_set", related_query_name="user", ) user_permissions = models.ManyToManyField( Permission, verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_name="my_auth_user_set", related_query_name="user", ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
PyTorch AssertionError: "Torch not compiled with CUDA enabled" in Django application
I'm encountering an issue in my Django application where I'm using PyTorch to initialize a model, and I'm getting an AssertionError with the message "Torch not compiled with CUDA enabled." This happens when trying to access GPU functionality. Details: Django Version: 3.0.5 Python Version: 3.6.2 PyTorch Version: CUDA Version: [12.3] Operating System: [win 11] Code Snippet: python Copy code # Relevant code snippet where the error occurs from torch import Model # ... def predict_page(request): model = Model(2).cuda() # ... Troubleshooting Steps Taken: Checked PyTorch installation. Verified CUDA installation. Updated PyTorch and CUDA to the latest versions. Conditionally initialized the model based on GPU availability. Checked GPU availability using torch.cuda.is_available(). Additional Notes: I've ensured that my system has a compatible GPU. I've restarted the Django development server after making changes. Question: What could be causing this error? Are there any specific configurations I need to check? Is there a compatibility issue between PyTorch, CUDA, and Django? Any help or guidance on resolving this issue would be greatly appreciated! AssertionError at /predict/ Torch not compiled with CUDA enabled Request Method: GET Request URL: http://127.0.0.1:8000/predict/ Django Version: 3.0.5 Exception Type: AssertionError Exception Value: Torch not compiled with CUDA enabled Exception Location: D:\ai\Deepfake_detection_using_deep_learning\Django … -
Django dynamic formsets hidden field error
I wanted to add button for dynamcially adding an instance of formset in dajngo. I use django-dynamic-formset for this. The problem is that if I add formset by the button and try to submit the below error appears: (Hidden field TOTAL_FORMS) This field is required. (Hidden field INITIAL_FORMS) This field is required. I read that it is caused by not including "form.managment_form" in a template, but I've included it: Here is a template code: {% extends "mainapp/base.html" %} {% block content %} {% load static %} {% load widget_tweaks %} <!-- Include necessary scripts and CSS for dynamic formset --> <script type="text/javascript" src="{% static 'jquery-3.7.1.min.js' %}"></script> <script type="text/javascript" src="{% static 'jquery.formset.js' %}"></script> <!-- <link rel="stylesheet" type="text/css" href="{% static 'formset/jquery.formset.css' %}"> --> <div id="input-div1"></div> <div class="input-div2"> <form method="post"> {% csrf_token %} {{ simulation_form.initial_amount.label_tag }} {{ simulation_form.initial_amount|add_class:"form-control"}} {{ simulation_form.number_of_simulations.label_tag }} {{ simulation_form.number_of_simulations|add_class:"form-control" }} {{ simulation_form.number_of_trades.label_tag }} {{ simulation_form.number_of_trades|add_class:"form-control" }} <br> <div class="strategy-formset"> {{ strategy_formset.management_form }} {% for form in strategy_formset %} {{ form.as_p }} {% endfor %} </div> <button type="submit" name="save" class="btn btn-primary">Submit</button> </form> </div> <script type="text/javascript"> $(function () { $('.strategy-formset').formset({ prefix: '{{ strategy_formset.prefix }}' }); }); </script> {% endblock %} Do you know what else can cause this error? Thanks in … -
Why I'm receiving the 'Connection time out' when I try to run the 'python manage.py migrate' code on putty?
Ok, I'm trying to deploy a Django project using EC2 instance I've already created an RDS/Postgree database and test it through my IDE before deploy it and it's working correctly But when I try to run the 'python manage.py migrate' code on putty I'm receiving this error angtradingdb.xxxxxxx.rds.amazonaws.com" (xxxxxxx), port 5432 failed: Connection timed out I've set 2 inbound rules on my RDS instance: First I put PostgreSQL as 'Type', 'TCP' as Protocol, 5432 as 'Port Range' and my IP as 'Source' Second inbound rule, it's the same thing but the VPC security group of my EC2 application as 'Source' I've done that before and those 2 rules where enough for the deployment to work Any idea of what can be causing this error? -
Django stops serving static files after a while
I recently built my first website with Django, loaded up all my static files, both js and scss scripts, and some pics. All works well, file uploads work, etc. Works fine after deploying to Azure as well. The problems started some time ago when my css stopped generating any changes in the pages layout (its not the scss mapping cause it works locally, and I see the changes in the css). I checked and when it occurs js files dont work also. It only loads up the changes up to my last commit and nothing after it, even though the server loads up the files from the disk with no errors. I thought it has something do to with version conflicts in the git but I resolved all of them, and it still didn't fix it. Tried restarting chrome, deleting cache files, hard reset. Collectstatic doesn't do anything at all. It sometimes works, and then just stops. Restarting the server, even the computer (I am desperate) doesn't work either. I checked the settings.py and the static files are all routed correctly: STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'mainsite/static' I am in debug mode when I develop the app locally. …