Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ordered Many-To-Many Custom Through Table, Now Field Has Duplicates
As the title indicates, when I try to order by my custom through table, the field now shows duplicates. It seems to be doing a left outer join, displaying all fields on both sides instead of showing only unique values, and distinct() seems to do nothing here. I'm using sqlite3 and distinct('field-name') isn't supported with sqlite3. Here's a dumbed-down summary of my code, showing only relevant fields: # Models class DataRepository(Base): class Meta: ordering = ('-updated_at',) name = models.CharField(max_length=100, unique=True) class Dataset(models.Model): class Meta: ordering = ('-updated_at',) name = models.CharField(max_length=100, unique=True) # Dataset name must be unique across BrainSTEM datarepositories = models.ManyToManyField(DataRepository, through="DatasetDatarepository", blank=True) # Data repositories where the data from this dataset is stored. Create private data repositories [here] class DatasetDatarepository(models.Model): class Meta: ordering = ('order',) unique_together = (('dataset', 'datarepository'),) dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE) datarepository = models.ForeignKey(DataRepository, on_delete=models.CASCADE) order = models.PositiveIntegerField(null=True, blank=True, default=0) # Admin class DatasetAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ( 'name', 'datarepositories', )}), ) form = DatasetForm # Form class DatasetForm(forms.ModelForm): class Meta: model = Dataset fields = [ "name", "datarepositories", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.fields.get('datarepositories', None): datarepositories = self.fields.get("datarepositories") dr = DataRepository.objects.none() projects = self.instance.projects.all() for project in projects: for group … -
AWS ElasticBeanstalk Django collectstatic expected string or bytes-like object, got 'NoneType'
I'm using django-storages on elastic beanstalk and when i try to collectstatic i get this error. Note that i can collectstatic with it fine on my local machine. I have validated that all ENV vars are set fine. 2024-06-06 16:20:37,084 P57299 [INFO] File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/core/management/base.py", line 459, in execute 2024-06-06 16:20:37,084 P57299 [INFO] output = self.handle(*args, **options) 2024-06-06 16:20:37,084 P57299 [INFO] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-06 16:20:37,085 P57299 [INFO] File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle 2024-06-06 16:20:37,085 P57299 [INFO] collected = self.collect() 2024-06-06 16:20:37,085 P57299 [INFO] ^^^^^^^^^^^^^^ 2024-06-06 16:20:37,085 P57299 [INFO] File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect 2024-06-06 16:20:37,085 P57299 [INFO] handler(path, prefixed_path, storage) 2024-06-06 16:20:37,085 P57299 [INFO] File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 368, in copy_file 2024-06-06 16:20:37,085 P57299 [INFO] if not self.delete_file(path, prefixed_path, source_storage): 2024-06-06 16:20:37,085 P57299 [INFO] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-06 16:20:37,085 P57299 [INFO] File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 278, in delete_file 2024-06-06 16:20:37,085 P57299 [INFO] if self.storage.exists(prefixed_path): 2024-06-06 16:20:37,086 P57299 [INFO] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-06 16:20:37,086 P57299 [INFO] File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/storages/backends/s3.py", line 541, in exists 2024-06-06 16:20:37,086 P57299 [INFO] self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) 2024-06-06 16:20:37,086 P57299 [INFO] File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/client.py", line 565, in _api_call 2024-06-06 16:20:37,086 P57299 [INFO] return self._make_api_call(operation_name, kwargs) 2024-06-06 16:20:37,086 P57299 [INFO] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-06 16:20:37,086 P57299 [INFO] File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/client.py", line 958, in _make_api_call 2024-06-06 16:20:37,086 P57299 [INFO] api_params = self._emit_api_params( … -
Django docxtpl subdoc merging doesn't merge all content
So I'm having a really annoying issue with django and docxtpl. I have a few placeholders in my document that I'm trying to replace. The placeholders content consists of html content. Im firstly setting this content in a subdoc based on the main doc (which works, the document is being saved and all the content that has been provided in the placeholder is inside of the sub_doc). Then Im trying to merge it, and here is where it gets really weird. As you can see I'm saving the merged document document.save("end_doc/doc.docx") # Save for local inspection. For some reason when I open this file it's empty. But my function returns the document in memory as you can see, in that file there is some content but it's missing some. So for example. If my placeholders content has a few elements, such as 5 <p> tags. It only shows 1 <p> tag in the merged file. But in the sub doc it shows every single tag. Thanks in advance from docx import Document from docxtpl import DocxTemplate from htmldocx import HtmlToDocx from docx import Document as _Document def convert_placeholders_to_text_in_doc(document, context, document_name): document = DocxTemplate(document) sub_docs = {} for placeholder, html_content in … -
The caller tried using channels rabbitmq on a different event loop than the one it was initialized with
im trying to initialize a queue rabbit consumer, process those message and send it to a websocket in django. But i got the title error. Im new at this kind of stuuf. Can someone explain me how can i make this work. This is my code: asgi.py import threading import django from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from apps.websocket import routing import asyncio from apps.websocket.services.message_processor import start_rabbitmq_consumer django.setup() application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns)), } ) def start_consumer_thread(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(start_rabbitmq_consumer()) consumer_thread = threading.Thread(target=start_consumer_thread, daemon=True) consumer_thread.start() consumer.py import asyncio import json import logging from aio_pika import connect, exceptions as aio_pika_exceptions import httpx from channels.layers import get_channel_layer from apps.websocket.services.data_extractor import extract_notification_data from core.settings import RABBIT_INTERSECTION_QUEUE, RABBIT_URL, API_TRACKER logger = logging.getLogger(__name__) async def start_rabbitmq_consumer(): """Inicializa el consumidor""" while True: try: connection = await connect(RABBIT_URL) await consume_messages(connection) except aio_pika_exceptions.AMQPConnectionError as e: await asyncio.sleep(5) except Exception as e: await asyncio.sleep(5) async def consume_messages(connection): """Iniciamos el consumo de mensajes de la cola de rabbit""" channel = await connection.channel() queue = await channel.declare_queue(RABBIT_INTERSECTION_QUEUE, durable=True) async for message in queue: async with message.process(): data = json.loads(message.body.decode()) await process_message(data) async def process_message(data): """Procesamos … -
How to uncomment django html comments?
In VSCode ctrl + / comments out code and usually the same shortcut is used to uncomment. {% extends 'master.html' %} {% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} {% endcomment %} however: {% comment %} {% comment %} {% extends 'master.html' %} {% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} {% endcomment %} {% endcomment %} Any work arounds or extensions that addresses this? I looked for any django specific extensions and did a search online. I saw a few issues listed about the shortcut not working. I was hoping someone else has stumbled upon a work around? Option 1 - Search for the comment and delete Option 2 - Delete with multiple cursors But... Hoping someone else found a better way. -
How to search query in Django JSONField Model?
I have been trying to resolve this issue for the past 2 days, but I have not found a solution yet. I have scoured the internet, Django Forum, and ChatGPT, and attempted over 50 methods, but nothing seems to work. Our Model: class Order(models.Model): Payment_Refrence = models.CharField(max_length=300, unique=True) Order_ID = models.CharField(max_length=300, unique=True, default=unique_order_id) OrderData = models.JSONField(max_length=100000, null=True, blank=True) Order Data Creation OrderDataCreate = { 'product_title': Product.title, 'product_description': Product.description, 'product_plans': ProductPlans, 'package': Package_name, } Dump Data: CreateOrder = Order.objects.create( OrderData=json.dumps(OrderDataCreate), ) After Dump Data in Database ~ code from Database "{\"product_title\": \"Redis API Implementition\", \"product_description\": \"Description Here\",}" I have implemented this to search: OrderData = Order.objects.all().order_by('-created_at') if SearchQuery: SearchQuery = inpvalidator.anyname_validation(SearchQuery) search_filters = Q(OrderData__contains={'product_title': SearchQuery}) OrderData = OrderData.filter(search_filters) print(f'Search Filtered=======>{OrderData.count()}') I even tried this: OrderData = OrderData.filter(OrderData__product_title__icontains=SearchQuery) I'm not getting any results. -
Browser Not Saving HttpOnly Cookie React/Django
I have a netlify frontend at app.mydomain.com, and a django ninja REST API at api.mydomain.com. When I submit to my login endpoint, the api returns successfully with the access key (which I store in app state) and a refresh token in the form of a secure, httponly cookie. I can see this cookie is returned by looking in the response headers in dev tools. The cookie however is not stored by the browser at all, I've gone through numerous other questions/answers and I believe I have implemented everything required, but it's still not working. My login API call from the frontend is: await fetch( AUTH_URL_OBTAIN, { method: RequestMethod.POST, headers: {"Content-Type": "application/json"}, body: JSON.stringify({username: formData.email, password: formData.password}), credentials: "include", }, ); On the backend, the cookie is set like this: response.set_cookie( key="refresh", value=refresh_token, expires=datetime.fromtimestamp(refresh_token_payload["exp"], timezone.utc), httponly=True, samesite="none", secure=True, path="/api/auth/web/token-refresh", domain=".mydomain.com", ) I also have the following settings set (substituting the values in for environment variables): CSRF_TRUSTED_ORIGINS = ["https://app.mydomain.com"] CORS_ALLOWED_ORIGINS = ["https://app.mydomain.com"] CORS_ORIGIN_WHITELIST = ["https://app.mydomain.com"] CORS_ALLOW_CREDENTIALS = True The login response provides the access token (which works as expected - I am able to make API calls using this just fine, and have credentials: include on all fetch requests) and the response … -
Trouble with Django migrations: No new migration files created despite all migrations applied
I am encountering an issue in my Django project where new migration files are not being created despite all migrations being applied. I have checked several possible causes, including database schema consistency, migration naming conflicts, and migration autodetection settings, but have not been able to resolve the issue. Problem Details: After running the makemigrations and migrate commands in Django, I expect to see new migration files created in my app's migrations directory. However, even though Django reports that all migrations are applied successfully, the expected migration files (0001_initial.py, 0002_something.py, etc.) are not generated. Output of each migration cmd Showmigrations output python manage.py showmigrations Travello_2 [X] 0001_initial admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial Checked for existing migration files: Ensured that there are no existing migration files with conflicting names or in alternative locations that might prevent Django from creating new ones. File Structure of App Migrations File structure -
404 page not displayed in django 4.2.6
I'm trying to create a custom 404 error page in my Django project. However, instead of displaying my custom page, the browser just shows a white page with the text "Not Found". Here's what I have done so far settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Path to the JSON file JSON_FILE_PATH = os.path.join(BASE_DIR, 'data', 'data.json') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-adfsdafdsafdsajfdslkfnkdsafnkdsnfdsaflk=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["127.0.0.1"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ] 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 = 'abiturtest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'abiturtest.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { … -
is there any other way to load the google api in jina django html template?
So i set up a sign in with google on google cloud, i havent implemented its logic in backend, do i need to implement logic in backend to see the google sign in widget? because i cannot see it, im sure its create client id i havent set anything in settings yes or anything so maybe i have to? Im trying to make the google sign in widget display, but im not seeing it, here is my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login Page</title> <script src="https://accounts.google.com/gsi/client" async></script> <style> body { font-family: Arial, sans-serif; background-color: #f4f4f4; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } .container { background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); text-align: center; } img { border-radius: 50%; width: 100px; height: 100px; object-fit: cover; margin-top: 10px; } p { color: #333; margin: 10px 0; } a { color: #007bff; text-decoration: none; font-weight: bold; } a:hover { text-decoration: underline; } .g_id_signin { margin-top: 20px; } </style> </head> <body> <div class="container"> {% if request.session.user_data %} <div> <p>Hi {{ request.session.user_data.given_name }} 🙂</p> <p>Your email is {{ request.session.user_data.email }}</p> <img src="{{ request.session.user_data.picture }}" alt="User picture"> <p>Click here to <a href="/sign-out">Sign … -
Cannot get django_sendfile2 to work with gunicorn, nginx, docker
Iam writing a webapp to help user create invoices. I manage to create and save the pdfs but I cannot get django_sendfile2 to save them. This is my django model with the upload_to function: def claim_path(instance, filename): return "archive/{0}_{1}/{2}_{3}/{4}".format( instance.guardian.last_name, instance.guardian.first_name, instance.patient.last_name, instance.patient.first_name, filename, ) class Claim(models.Model): patient = models.ForeignKey("Patient", on_delete=models.CASCADE) guardian = models.ForeignKey("Guardian", on_delete=models.CASCADE) start_date = models.DateField("Start Date") end_date = models.DateField("End Date") creation_date = models.DateField("Creation Date", default=datetime.now) sum = models.IntegerField("Claim Sum") pdf = models.FileField("Claim File", upload_to=claim_path) These are the important sections of settings.py: INSTALLED_APPS = [ ... "django_sendfile", ... ] # media MEDIA_URL = "/protected/" MEDIA_ROOT = "/protected/" # for django_sendfile2 SENDFILE_BACKEND = "django_sendfile.backends.nginx" SENDFILE_ROOT = "/protected/" SENDFILE_URL = "/protected/" this is the view that should serve the pdf (don't mind the name, later on I want to embed this on the website as a preview): def show_pdf_preview(request, claim_id): if request.user.is_authenticated: claim = Claim.objects.get(id=claim_id) if claim.guardian == request.user.guardian: logging.info(f"trying to show pdf preview using filename '{claim.pdf.path}'") return sendfile(request, claim.pdf.path) else: return HttpResponseForbidden else: return HttpResponseForbidden Here is my nginx default.conf: upstream django { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { alias /static/; } location /protected/ { internal; root /protected/; } … -
Django Forms update exsisting Data in Model with form.save()
I want to validate the form and then: Override an exsisting row in intuser if a row with samAccountName already exsist. Create a new intuser object when no intuser with samAccountName exsist. models.py class userdb(models.Model): samAccountName= models.CharField(max_length=50, primary_key=True) givenName= models.CharField(max_length=100) surName= models.CharField(max_length=100) accountExpires=models.DateField() enabled= models.BooleanField() lastLogonDate= models.DateField() passwordLastSet= models.DateField() department=models.CharField(max_length=50) usertype=models.CharField(max_length=3) def __str__(self): return f"{self.samAccountName}" class intuser(models.Model): samAccountName = models.OneToOneField( userdb, on_delete=models.CASCADE, primary_key=True, ) manager= models.CharField(max_length=100) sosafe=models.IntegerField() form.py class intUserInfoForm(forms.ModelForm): manager =forms.ModelChoiceField(queryset=userdb.objects.all(),widget=forms.Select(attrs={'class':'form-select','data-live-search':'true'})) class Meta: model=intuser fields = '__all__' widgets ={ 'sosafe':forms.TextInput(attrs={"class":"form-control"}) } Views.py elif(request.POST["usertypeID"]=="int"): intForm=intUserInfoForm(request.POST) if intForm.is_valid(): intForm.save() data={ "usertype":"int", 'form':intForm, } return render(request,'test.html',data) else: data={ "usertype":"int", 'form':intForm, } return render(request,'test.html',data) When I try to validate the form with is_valid() the method returns false when a intuser already exsists. This is probably because the OneToOneField in models.py. How can I validate all Fields except the samAccountName field. -
VS Code closes after opening
I just installed ubuntu 24. I'm a django developer and I've been working fine with Visual Studio Code, but today when I tried to open my vscode, while it was opening it closed without any error or message! :( I restarted my computer and reinstalled Vscode. But nothing that nothing:( note: I installed vscode from app center on ubuntu -
Ai chatbot in django using WitAI is only answering "There was an error processing you're request" to every question How do i fix that
I'm developing a chatbot using the Wit.ai API in a Django application. The chatbot interface is implemented in HTML and JavaScript. The bot is designed to take user input, send it to the Wit.ai API, and display the response. However, every time I send a message, the bot replies with "There was an error processing your request." I've double-checked the Wit.ai API call, and it seems to be correct. I suspect that the issue might be with how the response is handled or an issue with the authorization token. Below is the code for my HTML and JavaScript implementation: (Please don't use this code i've worked really hard on this) <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Intra AI Chatbot</title> <style> body { font-family: Arial, sans-serif; background: linear-gradient(to bottom right, #4a00e0, #8e2de2, #4a00e0); color: #fff; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; min-height: 100vh; /* Ensure full viewport height */ overflow: hidden; /* Hide overflow for shapes outside viewport */ position: relative; /* Set position to relative for absolute positioning of shapes */ } /* Animation keyframes */ @keyframes moveCircleUpDown { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-20px); } } @keyframes moveCircleLeftRight … -
How to handle file submission from normal HTML form
So I have created an HTML form to add Properties to the database and when I submit that form I expect the post data to go under request.POST and files (in my case images) go under request.FILES but the file field is also found in the request.POST… below are error SrcShot If you would like to see the code for views.py, models.py, and the HTML form for the solution, please leave a comment -
Implementing Centralized Authentication with JWT in Django Tenants
I'm developing a Django project that utilizes Django tenants for multi-tenancy management. I have implemented JWT authentication using rest_framework_simplejwt for user authentication. Now, I'm looking to centralize authentication across all tenants. I want to implement a single sign-on (SSO) solution where users can authenticate once and access all tenant resources without needing to log in separately for each tenant. However, I'm facing challenges integrating this with Django tenants and ensuring secure authentication. Current Setup: Here's an overview of my current setup: Django version: [5.0.4] Django tenants version: [3.6.1] Installed packages related to authentication: [simple jwt] Desired Solution: I'm seeking guidance on how to implement centralized authentication using JWT in Django tenants. Specifically, I want to: Understand the best practices for implementing SSO with Django tenants. Determine how to modify my existing JWT authentication setup to support SSO. Ensure that authentication is secure and user sessions are managed appropriately across tenants. Additional Information: Are there any potential security concerns I should be aware of? Are there any limitations or challenges with integrating SSO in Django tenants that I should consider? Any advice, code examples, or references to relevant documentation would be greatly appreciated. Thank you! -
After refreshing page gives CSRF verification failed. Request aborted. error
This is image attached, CSRF verification failed. Request aborted. When i refresh page after successfully login it ask for resubmit and when hit continue it shows "CSRF verification failed. Request aborted." error. In home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">reg</button> </form> </body> </html> In views.py from django.shortcuts import render, redirect from login_app.forms import LoginForm, UserRegistrationForm from django.contrib.auth import authenticate, login, logout from django.middleware.csrf import get_token from django.http import HttpResponseForbidden # Create your views here. def home(request): form = LoginForm() return render(request,'home.html',{'form':form}) def log_in(request): if request.method == 'POST': form = LoginForm(request.POST) # if request.POST.get('csrfmiddlewaretoken') == get_token(request): # return HttpResponseForbidden('invalid') if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] try: user = authenticate(email = email,password=password) if user is None: raise ValueError('not found') print(login(request,user)) login(request,user) return render(request,'after.html',{'name':user}) # return redirect('home') except ValueError as e: return redirect('home') else: form = LoginForm() return redirect('home') def log_out(request): logout(request) return redirect('home') In models.py from typing import Any from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.contrib.auth import authenticate # Create your models here. class CustomUserManager(UserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("Email can not be empty") … -
Django channels websocket non working properly
Iìm triing to create a simple chat app usign django channels i create a consumer on connect method i register all user to a personal group and when i sent a message the recieve method should sent it back to the target user group using the id of the target user included in the messagge. The action in not being triggered anyway class ChatConsumer(WebsocketConsumer): def connect(self): self.user = self.scope["user"] self.group_name = f"user_{self.user.id}_group" print("my group: ", self.group_name) self.accept() async_to_sync(self.channel_layer.group_add(self.group_name, self.channel_name)) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard(self.group_name, self.channel_name)) def receive(self, text_data): self.chat_id = self.scope["url_route"]["kwargs"]["chat_id"] data = json.loads(text_data) message_content = data["message"] recipient_user_id = data["recipient_user_id"] recipient = User.objects.get(id=recipient_user_id) message = Message.objects.create( chat_id=self.chat_id, owner=self.user, content=message_content ) message.recipients.add(recipient) recipient_group_name = f"user_{recipient_user_id}_group" async_to_sync( self.channel_layer.group_send( recipient_group_name, { "type": "chat_message", "message": message_content, "owner": self.user.id, }, ) ) def chat_message(self, event): message = event["message"] owner = event["owner"] self.send( text_data=json.dumps( { "message": message, "owner": owner, } ) ) -
vscode file not appearing in visual studio while setting up the python interpreter for django
to add the interpreter i go to "view" and then "command palette" and then i select "python: select interpreter" then i enter the interpreter path, the tutorial that im following says that a new file called vscode will appear but it doesnt appear for me, what am i suppose to do? im using visual studio code on windows and im trying to learn django i entered the interpreter path and i was expecting that the vscode tab/file will appear on the explorer tab in visual studio -
getting a "invalid user or password" error while testing a api
I am trying to built an log in API but getting a a "invalid user or password" error while testing. I have checked the database and user and password is correct and exists and correct. I have attached the log in view code and the error as a PNG format below enter image description here it is the log in view enter image description here and here is error. how to solve this issue ? I have checked database and user exists and I also printed user and password in terminal and the user and password also correct but still getting the error -
Whats the use of DSA in real world application?
Okay, I might sound stupid but I'm trying to understand the real-world application of DSA? I started learning DSA but I didn't know what I'm gonna make once I learned the whole thing? I'm a full stack developer and I know if there is a frontend developer his work is to code a site from a figma file or take the API coming from the backend and use Redux or other state management to do stuff or if there is a backend developer I know his work is to make backend parts building APIs working with DB and other stuff... But after learning DSA what I'm gonna build? What kind of work am I gonna do? Or after learning where I can use my DSA knowledge in my web apps? All I see are people talking about FAANG companies online and I haven't found that many videos or blogs on some DSA project in python. Can someone please clear my doubts it would be really appreciated I'm so confused right now. -
Django startproject [WinError2]
This is my first time using django so maybe I am missing something obvious. When I try to create a new project using command django-admin startproject main i get this error CommandError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\edgar\\Documents\\main'. I thought django creates this directory? That's what I see in all tutorials. Very confused I tried running command prompt as an administrator as well as uninstalling and reinstalling django. Also tried reinstalling python which still didn't work. Tried running in VSCode terminal. Nothing seems to be working. If I manually create the directory then i get an error saying 'manage.py' does not exist in the directory. -
Python - Django - MySQL #need to add distinct() after select_related().distinct() in views.py
class AdListView(ListView): model = Ad # Specify the model you're working with template_name = "ads/ad_list.html" def get(self, request): strval = request.GET.get("search", False) if strval: query = Q(title__icontains=strval) query.add(Q(text__icontains=strval), Q.OR) ad_list = Ad.objects.filter(query).select_related().distinct().order_by('-updated_at') else: ad_list = Ad.objects.all().select_related().distinct().order_by('-updated_at') # Apply distinct() explicitly ad_list = ad_list.distinct() if request.user.is_authenticated: favorites = list(request.user.favorite_ads.values_list('id', flat=True)) else: favorites = [] for obj in ad_list: obj.natural_updated = naturaltime(obj.updated_at) ctx = {'ad_list': ad_list, 'favorites': favorites, 'search': strval} return render(request, self.template_name, ctx) so this is ads/views.py there's a ads/models.py, ads/forms, ads/urls.py and other files, but the one that the grader is complaining is this views.py... 3806 characters of HTML retrieved Test completed: Found menu bar at the top of the page Found more than one ad when searching for 'HHGTTG_42 1717639962'. You probably need to add distinct() after select_related().distinct() ... in your views.py so i tried using the select_related().distinct() and adding it after, but is not working :( -
Django: Better way to process data from my models.py than doing it in my views.py
Currently, I am processing a lot of information in views.py, which feels like the incorrect place to do it. Is there a better/place way to process this information? It works, but it doesn't seem like I am using Django to its potential. views.py - Where I am doing all the information processing def stats(request): user = request.user deck_list = Deck.objects.filter(user=request.user).annotate( win_count=Count('game', filter=Q(game__outcome='Win', game__user=request.user)), loss_count=Count('game', filter=Q(game__outcome='Loss', game__user=request.user)), draw_count=Count('game', filter=Q(game__outcome='Draw', game__user=request.user)), incomplete_count=Count('game', filter=Q(game__outcome='Incomplete', game__user=request.user)), count_1_7=Count('game', filter=Q(game__mull='1st 7', game__user=request.user)), count_2_7=Count('game', filter=Q(game__mull='2nd 7', game__user=request.user)), count_6=Count('game', filter=Q(game__mull='6', game__user=request.user)), count_5=Count('game', filter=Q(game__mull='5', game__user=request.user)), count_4=Count('game', filter=Q(game__mull='4', game__user=request.user)), count_3=Count('game', filter=Q(game__mull='3', game__user=request.user)), count_2=Count('game', filter=Q(game__mull='2', game__user=request.user)), count_1=Count('game', filter=Q(game__mull='1', game__user=request.user)), ) # Totals for player total_game = Game.objects.filter(user=request.user).count() total_win = Game.objects.filter(user=request.user, outcome='Win').count() total_loss = Game.objects.filter(user=request.user, outcome='Loss').count() total_draw = Game.objects.filter(user=request.user, outcome='Draw').count() total_incomplete = Game.objects.filter(user=request.user, outcome='Incomplete').count() average_hand_size1_7 = Game.objects.filter(user=request.user, mull='1st 7').count() average_hand_size2_7 = Game.objects.filter(user=request.user, mull='2nd 7').count() average_hand_size6 = Game.objects.filter(user=request.user, mull='6').count() average_hand_size5 = Game.objects.filter(user=request.user, mull='5').count() average_hand_size4 = Game.objects.filter(user=request.user, mull='4').count() average_hand_size3 = Game.objects.filter(user=request.user, mull='3').count() average_hand_size2 = Game.objects.filter(user=request.user, mull='2').count() average_hand_size1 = Game.objects.filter(user=request.user, mull='1').count() average_hand = 0 if total_game == 0: pass else: average_hand = (average_hand_size1_7 * 7 + average_hand_size2_7 * 7 + average_hand_size6 * 6 + average_hand_size5 * 5 + average_hand_size4 * 4 + average_hand_size3 * 3 + average_hand_size2 * 2 + average_hand_size1) / total_game context = … -
Change widget of modelformset field to RadioSelect without defining a form object?
In Django, I am instantiating a modelformset as follows (straight from here): MyFormSet = modelformset_factory( MyModel, fields=["one", "two", "three"], extra=0) fs = MyFormSet(queryset=MyModel.objects.filter(field=a_value)) So, no form object at all, it just picks the fields I want. However, one of those fields (say "two") is rendered as a drop-down, and I want it as a RadioSelect. Is there a way to change the widget of "two" to RadioSelect in a simple way, or do I have to declare a form object to customize that?