Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problem in getting user email in django app with sicial auth
hello i have a django e commerce app that have google social auth when new users create an account we create a some % of dicount code for them i have UserIdentifier class that when users create new account i save either their phoen number or their email address to then when a new users create account i check if we have this users before or not to stop them from abusing the discount code i have this pipeline : from django.contrib.auth import get_user_model, login from django.shortcuts import redirect from .models import Profile,UserIdentifier import re User = get_user_model() def save_profile(backend, user, response, *args, **kwargs): if backend.name == 'google-oauth2': email = response.get('email') first_name = response.get('given_name') last_name = response.get('family_name') unique_identifier = email user_exists_before = UserIdentifier.objects.filter(identifier=unique_identifier).exists() if not user_exists_before: UserIdentifier.objects.create(identifier=unique_identifier) # Update user fields if email: user.email = email if user.phone_number and not re.match(r'^\d{11}$', user.phone_number): user.phone_number = None user.first_name = first_name user.last_name = last_name user.save() # Update or create profile profile, created = Profile.objects.get_or_create(user=user) profile.first_name = first_name profile.last_name = last_name profile.email = email profile.save() # Handle login and redirection request = kwargs.get('request') # Get the request object from kwargs if request: user.backend = 'social_core.backends.google.GoogleOAuth2' login(request, user) # Log the user in regardless of … -
Django model foreign key to whichever model calls it
I am getting back into Django after a few years, and am running into the following problem. I am making a system where there are 2 models; a survey, and an update. I want to make a notification model that would automatically have an object added when I add a survey object or update object, and the notification object would have a foreign key to the model object which caused it to be added. However I am running into a brick wall figuring out how I would do this, to have a model with a foreign key which can be to one of two models, which would be automatically set to the model object which creates it. Any help with this would be appreciated. I am trying to make a model that looks something like this (psuedocode): class notification(models.model): source = models.ForeignKey(to model that created it) #this is what I need help with start_date = models.DateTimeField(inherited from model that created it) end_date = models.DateTimeField(inherited from model that created it) Also, just to add some context to the question and in case I am looking at this from the wrong angle, I am wanting to do this because both surveys and … -
Use the same logging.Handler in different main files
Cheers! I am developping a Django Projekt and I want to display my backend loggings to the forntend. Thats why i created a central logging Handler that pushes logs into a buffer. Every 20 sec my frontend sends a request to flush the buffer and display the log events. Central Loging Class (log.py): import logging class BufferedLogHandler(logging.Handler): def __init__(self): super().__init__() self.log_buffer = [] # Lokaler Puffer für Logs def emit(self, record): log_entry = self.format(record) # Format den Log-Eintrag self.log_buffer.append(log_entry) def create_external_log(self, level=None, timestamp=None, message=None): asctime = timestamp msg = message record = logging.LogRecord( level=level, msg=msg, asctime=asctime, lineno=0, exc_info=None, args=None, name= None, pathname="frontend", ) self.emit(record=record) return BufferedLogHandler.create_empty_response() def flush_buffer(self): logs_to_send = self.log_buffer[:] print(f'logs_to_send:{logs_to_send}') print("---------------------") self.log_buffer = [] return logs_to_send @staticmethod def create_empty_response(): response = {'message':""} return response buffered_handler = BufferedLogHandler() def setup_logger(bufferedHandler): # Den Logger holen (Root-Logger oder benannten Logger) logger = logging.getLogger() # Du kannst auch den Root-Logger verwenden # Setze das Log-Level (z.B. DEBUG, INFO) logger.setLevel(logging.DEBUG) # Erstelle einen Handler (z.B. für Konsole oder Datei) file_handler = logging.FileHandler('myapp.log') # Für eine Log-Datei # Erstelle ein Format für die Log-Nachrichten formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d - %(message)s') # Setze das Format für beide Handler bufferedHandler.setFormatter(formatter) file_handler.setFormatter(formatter) … -
Django ManyToMany through model/table indexing
For ManyToMany relationships Django will automatically create a trough model/table. For example for: class Magazine(models.Model): pass class Article(models.Model): magazines = models.ManyToManyField('Magazine', related_name='articles') there will be a Article.through manager and model. The associated table will have two separate indices for each of the columns. Two questions: How do I create a new index on both columns? I could run a raw SQL query to do it, but I wonder if there is a way to do something similar to how index_together, which is easy to maintain and track. Is there a reason why Django doesn't automatically add an index to both columns? In my test, I manually created the index and saw Postgres hit it a lot and gain performance. -
Django Project, browser not making HTTP GET request for static files in development server
Hello I’m trying to load my static files to my templates but they’re not getting passed to my browser. When I look at the developer tools, I don’t see my Javascript and HTML files being passed to the browser. For some reason when I make a request for the page that I'm trying to include the static files on, I get 'GET /login/ HTTP/1.1'. The browser isn't even making a request for the static files. When I enter in the URL for the static files such as domain/static/styles.css or domain/static/index.js, I get sent to the file and no issue occurs. It’s just for some reason when I enter the page that the static files should be included on, browser doesn’t make a request for the static files. -
Python/Django Dynamic Form creation
I have an html page, which have dropdown field. I had load dropdown values from DB. Now selecting dropdown, the required fields related to value may be load, which has been described in 1 DB Table. so how is it possible? I have done like this... class VenDocMastForm(forms.ModelForm): doc_cat = forms.ChoiceField( label='Document Type*', choices=[(0, 'SELECT')] + [(dt.doc_type_id, dt.doc_type_desc) for dt in ven_doc_mast.objects.all()], widget=forms.Select(attrs={'class': 'col-sm-12 form-control-sm dropdown'}) ven_doc_path = forms.FileField( label='Upload Document File', required=False, # This can be set to True if file upload is mandatory widget=forms.ClearableFileInput(attrs={'class': 'form-control btn-outline-primary'}) ) class Meta: model = ven_doc_hdr # Model used for saving data fields = [ 'doc_id', 'ven_id', 'doc_reg_no', 'doc_reg_dt', 'doc_last_dt', 'doc_reg_cat', ] widgets = { 'doc_id': forms.NumberInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Document Type ID'}), 'ven_id': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Vendor ID'}), 'doc_reg_no': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Registration Number'}), 'doc_reg_dt': forms.DateInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'type': 'date'}), 'doc_last_dt': forms.DateInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'type': 'date'}), 'doc_reg_cat': forms.TextInput(attrs={'class': 'col-sm-12 form-control-sm dropdown', 'placeholder': 'Enter Registration Category'}), } def save(self, commit=True): # Handle form saving to ven_doc_hdr instance = super().save(commit=False) # Save ven_doc_dtl entry if file is uploaded if self.cleaned_data.get('ven_doc_path'): ven_doc_dtl_instance = ven_doc_dtl( doc_id=instance.doc_id, ven_doc_type_id=instance.doc_id, # Example: Mapping the document type ID from … -
Best Practice for Creating a Model's Record in `post_save` Signal While Maintaining Data Integrity in Django
I am working on a Django application where I need to automatically create a Setting record with default values whenever a new User is created. My current implementation uses the post_save signal of the User model to handle this logic. from django.db.models.signals import post_save from django.db import transaction from django.contrib.auth.models import User from myapp.models import Setting @receiver(post_save, sender=User) def create_default_setting(sender, instance, created, **kwargs): if created: transaction.on_commit(lambda: Setting.objects.create(user=instance)) I used transaction.on_commit to make sure that the creation of the Setting record happens only after the User creation transaction is committed, to avoid issues where the User instance might not yet exist in the database. However, this separates the Setting creation from the User creation transaction. If for any reason the Setting creation fails (e.g., validation errors, database issues), I end up with a User record without a corresponding Setting, which violates data integrity. On the other hand, if I don't use transaction.on_commit and create the Setting directly in the post_save signal, there is a risk of attempting to create a Setting record before the User instance is fully saved in the database, or creating a Setting even when the User creation fails due to an uncommitted or rolled-back transaction. This leaves … -
Proper approach to login user in Django channels websockets?
Developing a dashboard using Django channels, two different consumers are implemented, UserConsumer and RequestConsumer. In UserConsumer methods like login, logout and get_user are implemented. The user Authentication is being done using OTP code sent to user mobile so that a user_send_code method is in charge of sending SMS while the user_login method verifies the code sent by user. UserConsumer is implemented as follow: class UserConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() async def receive_json(self, content=None, **kwargs): action = content.get("action", "user.get_user") if action == "user.login": await self.user_login(content) elif action == "user.send_code": await self.user_send_code(content) elif action == "user.logout": await self.user_logout() else: await self.user_get_user() async def user_send_code(self, content): await self.send("we will send sms to: {}".format(content['mobile'])) if check_mobile_pattern(content["mobile"]): code = random.randint(1111, 9999) self.scope[VERIFY_CODE] = code self.scope[MOBILE] = content["mobile"] result = await send_sms(content["mobile"], code) if result: await self.send_json(send_code(200)) else: await self.send_json(send_code(400)) else: await self.send_json(send_code(SystemErrorCodes.InvalidMobilePattern)) async def user_get_user(self): if self.scope['user'].is_authenticated: await self.send_json({"id": self.scope['user'].id}) else: await self.send_json(send_code(SystemMessageCodes.AnonymousUserMessage)) async def user_login(self, content): verify_code = self.scope.get("verify_code") code = content.get("code") mobile = self.scope.get(MOBILE) if mobile is not None and verify_code is not None and code == verify_code: user = await load_user_by_mobile(mobile) del self.scope[VERIFY_CODE] # login the user to this session. await login(self.scope, user) # save the session (if the session backend … -
Django app failing to get deployed on Azure web service
I have a Django app that was running without issues till 2 days back on Azure. I then added some Azure OAI code using semantic-kernel and since then haven't been able to complete the deploy step of github actions workflow to deploy the app. To use semantic-kernel, I had to update to python 3.11 from python 3.8 on Azure. The deployment runs for about 40 mins and then errors out. From docker logs, I see the following issue:ModuleNotFoundError: No module named 'django' 2024-12-30T01:12:32.6106267Z Using packages from virtual environment antenv located at /home/site/wwwroot/antenv. 2024-12-30T01:12:32.6117557Z Updated PYTHONPATH to '/opt/startup/app_logs:/home/site/wwwroot/antenv/lib/python3.11/site-packages' 2024-12-30T01:12:35.1840122Z [2024-12-30 01:12:35 +0000] [84] [INFO] Starting gunicorn 23.0.0 2024-12-30T01:12:35.3134084Z [2024-12-30 01:12:35 +0000] [84] [INFO] Listening at: http://0.0.0.0:8000 (84) 2024-12-30T01:12:35.3205313Z [2024-12-30 01:12:35 +0000] [84] [INFO] Using worker: sync 2024-12-30T01:12:35.3321195Z [2024-12-30 01:12:35 +0000] [89] [INFO] Booting worker with pid: 89 2024-12-30T01:12:35.4238708Z [2024-12-30 01:12:35 +0000] [89] [ERROR] Exception in worker process 2024-12-30T01:12:35.4473148Z Traceback (most recent call last): 2024-12-30T01:12:35.4475461Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/arbiter.py", line 608, in spawn_worker 2024-12-30T01:12:35.4476786Z worker.init_process() 2024-12-30T01:12:35.4477986Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/workers/base.py", line 135, in init_process 2024-12-30T01:12:35.4479379Z self.load_wsgi() 2024-12-30T01:12:35.4480603Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/workers/base.py", line 147, in load_wsgi 2024-12-30T01:12:35.4481752Z self.wsgi = self.app.wsgi() 2024-12-30T01:12:35.4484237Z ^^^^^^^^^^^^^^^ 2024-12-30T01:12:35.4485531Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/app/base.py", line 66, in wsgi 2024-12-30T01:12:35.4486749Z self.callable = self.load() 2024-12-30T01:12:35.4487911Z ^^^^^^^^^^^ 2024-12-30T01:12:35.4489069Z File "/opt/python/3.11.10/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line … -
How to Customize Indigo Theme and CSS Variables for Micro-Frontends in Open edX?
I’m working with Open edX, specifically using the Indigo theme and Micro-Frontends (MFEs). I want to customize the theme by setting CSS variables or tokens to maintain consistent branding across the platform. However, I’ve run into some challenges and am not sure how to proceed. My Setup: Open edX platform is hosted with the Indigo theme. I’m working with Tutor for managing the Open edX instance. The Micro-Frontends (React-based) are running on apps.local.edly.io. What I’ve Tried: I’ve looked into modifying the Indigo theme’s Sass variables (e.g., $primary-color) but couldn’t figure out the process to make these changes take effect. I don’t have React components inside the indigo-theme folder to directly manage styles or tokens for MFEs. I’ve come across mentions of the edx/brand package, but I’m unclear on how to use it to integrate the custom styles with MFEs. Questions: How can I customize the Indigo theme to define CSS variables or tokens? Is it possible to ensure these customizations are applied across both the core platform and the MFEs? If yes, what’s the best way to do this? Do I need to modify or replace the edx/brand package for this, and how do I integrate it properly with Tutor-managed … -
Websocket 404 error after deploying to the domain
I setup websockets (chat module) in my Django application, it is working fine on my local machine but when I deployed my app to amazon ec2 instance with containerization it says 404 Not Found while testing via the postman. My ASGI container logs also say the same: WARNING Not Found: /chat/1/ IP:47942 - - [XX:XX:XX] "GET /chat/1/" 404 4479 Note that there is no problem with Docker containers - I tried on containers too on my local machine, and it worked. I have asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cruze_development.settings') application = get_asgi_application() from cruze_development.middleware import JWTAuthMiddleware from cruze_development.consumers import ClubFeedConsumer, RideLocationConsumer application = ProtocolTypeRouter({ "http": application, "websocket": JWTAuthMiddleware( URLRouter([ path('ws/chat/<str:room_name>/', ClubFeedConsumer.as_asgi()), path('ws/location/<str:ride_id>/', RideLocationConsumer.as_asgi()), ]) ), }) wss://mydomain.com/ws/chat/1/ I am trying with both ws and wss Help me solve it, man! -
ODBC Driver 18 Heroku Django connection
I have database (Azure SQL) which I need to interact with on my Django backend and also I do have credentials like client id, client secret, tenant id. So basically I'm connecting via Azure App to this database. I run into a problem when Heroku on its side doesn't have ODBC Driver 18 installed so I followed https://github.com/matt-bertoncello/python-pyodbc-buildpack the buildpack which pre-installs ODBC Driver 17 however I faced another issue with that where my openssl version is 3.0 or something but it requires maximum of 1.1, anyway if this issue is settled I still left with ODBC Driver 17 version which makes impossible to connect via Azure APP credentials, so only ODBC Driver 18 would work for me. My question is simple, does anyone tried to do the same with heroku and Azure SQL, can you just share steps you take to connect to this database, also are you using VPN for backend? Cuz it seems like proxies can't handle the connection for db as well. Lmao, so many questions asked sorry about that, hope to find the answer here. Stackoverflow seems to be almost empty on that sort of questions, read around 10 posts related to this topic none … -
SSL: CERTIFICATE_VERIFY_FAILED when submitting forms in Django run on Windows VPS with Apache web server
I have a Django website hosted on a VPS (OS Windows server 2019). The web server is Apache 2.4 and Python version is 3.12.8. A Digicert SSL certificate successfully installed and the website is working in production under https. However, I get this error when I try to submit a login or signup form from the website in production: URLError at /login-page/ <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)> Here is the complete error traceback: URLError at /login-page/ <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)> Request Method: POST Request URL: https://www.mywebsite.com/login-page/ Django Version: 5.0.6 Exception Type: URLError Exception Value: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)> Exception Location: C:\Python 3.12.8\Lib\urllib\request.py, line 1347, in do_open Raised during: users_authentication.views._wrapped_view Python Executable: C:\Apache24\bin\httpd.exe Python Version: 3.12.8 Python Path: ['C:\\Apache24\\htdocs\\project', 'C:\\Python 3.12.8\\python312.zip', 'C:\\Python 3.12.8\\DLLs', 'C:\\Python 3.12.8\\Lib', 'C:\\Apache24\\bin', 'C:\\Python 3.12.8', 'C:\\Python 3.12.8\\Lib\\site-packages'] C:\Python 3.12.8\Lib\urllib\request.py, line 1344, in do_open h.request(req.get_method(), req.selector, req.data, headers, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … C:\Python 3.12.8\Lib\http\client.py, line 1336, in request self._send_request(method, url, body, headers, encode_chunked) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … C:\Python 3.12.8\Lib\http\client.py, line 1382, in _send_request self.endheaders(body, encode_chunked=encode_chunked) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … C:\Python 3.12.8\Lib\http\client.py, line 1331, in endheaders self._send_output(message_body, … -
Account Merging with Google Login and Normal Registration
In my Django project, I have both normal registration and Google login. If a user registers normally and provides their email, and then tries to log in with Google using the same email, the classic login screen appears. What I want is this: If a user logs in with Google first and then tries to log in with the same email via normal registration, or if they register normally and later try to log in with Google using the same email, I want both methods to lead to the same account. In other words, regardless of whether they log in with Google or normal registration, the user's information should be merged and they should access the same account in both cases. socal login sections in settings.py: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '<722444511487-2i7e9u3urlugcp2cp6slp09jjg7kgdg3.apps.googleusercontent.com>' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '<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>' SOCIALACCOUNT_LOGIN_ON_GET=True ACCOUNT_UNIQUE_EMAIL = True EMAIL_VERIFICATION_METHOD = 'email' # settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 # TLS GENELLİKLE 587 PORTUNU KULLANIR SSL İSE GENELLİKLE 465 PORTUNU KULLANIR EMAIL_USE_TLS = True # TLS SSL'E GÖRE DAHA MODERN VE GÜVENLİDİR EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' views.py: def loginUser(request): if (request.user.is_authenticated): messages.error(request,"Giriş Yapılıyken Giriş Yapamazsın!") return redirect("index") form = LoginForm(request.POST or None) if (form.is_valid()): login(request,form.cleaned_data["user"]) messages.success(request,"Başarıyla Giriş … -
How to move django models to new server
I have two options and not know which is the best: 1 - After coping Django files, delete migration files, so after makemigrations and migrate tables will be created. And after that import dumped database (only data). or 2 - Import dumped database (full), everything (create tables and data). -
I got this error while solving some issues in my project
Traceback (most recent call last): File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024\admin\files.py", line 1, in from rest_framework.authtoken.models import Token File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\rest_framework\authtoken\models.py", line 9, in class Token(models.Model): File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\rest_framework\authtoken\models.py", line 15, in Token settings.AUTH_USER_MODEL, related_name='auth_token', ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\django\conf_init_.py", line 81, in getattr self.setup(name) File "C:\Users\hp\Downloads\examination-project-repo\Online-Examination-System-CUH-2024.venv\Lib\site-packages\django\conf_init.py", line 61, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
'WSGIRequest' object has no attribute 'get' django 5.1.4
hey guys im new to django and in my first project i trying to save the cart of a visitor in session when i try to add some product in cart of session i have this error says < WSGIRequest object has no attribute 'get' i use a class for cart in my project and in init i check if 'cart' exists in session or no then create a key for 'cart' like this : in class Cart: class Cart: def __init__(self, request): """ Initialize The Cart """ self.request = request self.session = request.session cart = self.session.get('cart') if not cart: cart = self.session['cart'] = {} self.cart = cart # add a product to session cart: def add(self, product, quantity=1): """ Add The Specified Product To The Cart If Exists """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': quantity} else: self.cart[product_id]['quantity'] += quantity self.save() i also use another way for check if 'cart' exists in session: if 'cart' not in request.session: self.cart = self.session['cart'] = {} and still have the same issue... form for using the cart: class AddToCartProductForm(forms.Form): QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 30)] quantity = forms.TypedChoiceField(choices=QUANTITY_CHOICES, coerce=int, label=_('Quantity')) view: def add_to_cart_view(request, product_id): … -
I HAVE SOME QUESTION FOT PYTHON DJANGO ERROR
Django error Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON.How could i solve this error for website development when it return 500 error code. solution of bug for django developing -
How Can a Beginner Web Developer Start Getting Clients Without Prior Experience?
I'm a 16-year-old self-taught web developer. I’ve been learning technologies like UI/UX, Bootstrap, and Django. I want to start earning money by getting clients, but I’m facing some challenges: Lack of Experience: Many freelancing sites require prior experience, but I don’t have any yet. How can I overcome this chicken-and-egg problem? Finding Clients: I don’t know where to look for my first client or how to convince someone to hire me without a portfolio of work. I’ve been trying various freelancing platforms, but I keep running into the same issue: most clients want experienced developers. For those who’ve been in this situation, how did you find your first client? Do you have advice for someone like me who is just starting out? Thank you in advance! -
Unable to Send OTP via Twilio in Django
I'm working on implementing an OTP system in my Django project using Twilio. I've successfully obtained a Twilio phone number, but the OTP message is not being sent to the user's mobile number. Below are the details of my setup: Code Implementation views.py: def send_otp_view(request): if request.method == "POST": data = json.loads(request.body) phone_number = data.get('phone_number') # Generate a random 6-digit OTP otp = random.randint(100000, 999999) # Send OTP via Twilio (or any other SMS provider) try: client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) message = client.messages.create( body=f"Your OTP is {otp}. Please use this to verify your number.", from_=settings.TWILIO_PHONE_NUMBER, to=phone_number ) # Optionally, store the OTP in a session or database request.session['otp'] = otp request.session['phone_number'] = phone_number return JsonResponse({'status': 'success', 'otp': otp}) # Return OTP for validation except Exception as e: return JsonResponse({'status': 'error', 'message': str(e)}) return JsonResponse({'status': 'error', 'message': 'Invalid request'}) def address_view(request): if request.user.is_authenticated: user_addresses = Address.objects.filter(user=request.user) if request.method == "POST": # Get the OTP from the form entered_otp = request.POST.get("otp") # Check if the OTP matches if entered_otp == str(request.session.get('otp')): # Proceed with saving the address if OTP is correct mobile = request.POST.get("mobile") email = request.POST.get("email") pin = request.POST.get("pin") region = request.POST.get("region") address = request.POST.get("address") landmark = request.POST.get("landmark") name = request.POST.get("name") … -
Django or Different Framework?
I currently have a Django application, which is using Datatables. I'm thinking about creating views to load data into the datatable but load different data on the same page (into that same datatable). This way the page doesn't have to keep refreshing for each category. My question is, doing this, I won't have much need for the Django Template other then some basic things. Is this normal to do in Django or should I be using a different framework? -
Inconsistent URL error in Django from following along to Beginner YT tutorial
As you can see in the first screenshot, /products/new isn't showing up as a valid URL although I followed the coding tutorial from YouTube exactly. For some reason there's a blank character before "new" but no blank space in the current path I'm trying to request. I don't know if that's normal or not. I'm using django version 2.1 if that matters The URL does work for products/salt/. What's weird is the URL used to be products/trending/ but I got the same error so I randomly changed the URL to salt and it started working for me. [Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/new/ Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order: admin/ products/ products/ salt products/ new The current path, products/new/, didn't match any of these.]1 from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') def trending(request): return HttpResponse('Trending Products') def new(request): return HttpResponse('New Products')[2] from django.urls import path from . import views urlpatterns = [ path('', views.index), path('salt', views.trending), path('new', views.new)[3] -
Pylance use Django V4 after Upgrading to Django V5
I have a model like this: class Test(models.Model): a = models.TextField(null=True, blank=True) b = models.TextField(null=True, blank=True) class Meta: constraints = [ models.CheckConstraint( condition=models.Q(a__isnull=False) | models.Q(b__isnull=False), name="not_both_null", ), ] After migrating to Django V5, VS code is reporting: However the check constraint has been updated in Django V5: It feels like Pylance is using "cached" old version somehow. I have tried following ways: Update Python and Pylance extensions to the latest. Restart VS Code/reload window. Restart Pylance server. Set 'python.analysis.extraPaths' to my venv. Reinstall Pylance. Any other ways I can try? -
Make Django parse plus in url as plus
I have an url, that contains a plus: /?a=3+4. Is it possible to make Django to treat plus as plus, not as whitespace? Thank you. Django 5.1.3 -
Multiple file uploead. Getting error file upload Field 'id' expected a number but got <InMemoryUploadedFile: test image.jpg (image/jpeg)>
I have a model that has a manytomany to another model. Its a competition and the other model is sponsor images (sponsor_logo) for the competition. I'm creating a form to create a competition and all of the associated information. I keep getting this error when submitting the from and I can't figure out why. I am creating the sponsor object, assigning the appropriate fields, saving and linking to the competition model. But I get the type error on the ID. Shouldn't that pass between these objects? class Competition(models.Model): name = models.CharField(max_length=255) registration_deadline = models.DateTimeField() allowed_divisions = models.ManyToManyField(Division, related_name='allowed_competitions') allowed_weight_classes = models.ManyToManyField(WeightClass, related_name='allowed_competitions') federation = models.ForeignKey(Federation, on_delete=models.SET_NULL, null=True, blank=True) sponsor_logos = models.ManyToManyField('Sponsor', blank=True) def __str__(self): return self.name class Sponsor(models.Model): name = models.CharField(max_length=255) logo = models.ImageField(upload_to='sponsor_logos/') def __str__(self): return self.name views.py class CompetitionCreateView(LoginRequiredMixin, generic.CreateView): model = Competition form_class = CompetitionForm template_name = 'competitions/competition_form.html' success_url = reverse_lazy('competitions:competition_list') def form_invalid(self, form): print("Form is invalid") print(form.errors) return super().form_invalid(form) def form_valid(self, form): form.instance.organizer = self.request.user competition = form.save(commit=False) try: if self.request.FILES.getlist('sponsor_logos'): competition.save() for logo in self.request.FILES.getlist('sponsor_logos'): sponsor = Sponsor.objects.create( name=logo.name # Or any other suitable name ) sponsor.logo.save(logo.name, logo, save=True) competition.sponsor_logos.add(sponsor) else: competition.save() except Exception as e: return super().form_valid(form)class