Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to know if an email address exists before creating a user in Django?
I have a RegistrationSerializer in which I crate a user with is_verfied=False. And I wanted to prevent bad intended users to create fake accounts. Even if they can't login due to the email verification step, it would still be a headache if someone just posted a lot of fake users. class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'password', 'cpf', 'is_active') extra_kwargs = { 'password': {'write_only': True} } def validate(self, data): return data def create(self, validated_data): user = User.objects.create_user(**validated_data) token = generate_email_verification_token.make_token(user) verification_url = f"{os.environ.get('FRONTEND_URL')}/verify-email?uid={user.id}&token={token}" subject = "..." plain_message = ( "...{verification_url}..." ) html_message = f""" ...{verification_url}... """ send_mail( subject, plain_message, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=html_message, fail_silently=False, ) return user And I tried to except send_email to delete the created user if there was any problems while trying to send the email, but nothing worked: try: send_mail( subject, plain_message, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=html_message, fail_silently=False, ) except BadHeaderError: # If mail's Subject is not properly formatted. print('Invalid header found.') User.objects.delete(id=user.id) raise ValidationError except SMTPException as e: # It will catch other errors related to SMTP. User.objects.delete(user=user) print('There was an error sending an email.'+ e) raise ValidationError except: # It will catch All other possible errors. User.objects.delete(user=user) print("Mail Sending Failed!") raise ValidationError So, … -
DRF: How can I validate data vs instance when many=True?
I am using a DRF serializer to update data in bulk. This is how I instantiate the serializer: # Order incoming data and DB instances data = sorted(data, key=lambda x: x["id"]) instances = WorksheetChecklistItem.objects.filter(id__in=(row["id"] for row in data)).order_by("id") # Serialize and save serializer = update.WorksheetChecklistItemSerializer(instance=instances, data=data, many=True) if not serializer.is_valid(): # ... more logic ... And this is the serializer: class WorksheetChecklistItemSerializer(serializers.ModelSerializer): class Meta: model = WorksheetChecklistItem fields = ["id", "value", "outcome"] def update(self, instance, validated_data): instance.outcome = validated_data.get("outcome", instance.outcome) instance.value = validated_data.get("value", instance.value) instance.done = instance.outcome is not None instance.save() return instance def validate(self, data): """Custom validation for the checklist item.""" instance = self.instance if not instance: raise serializers.ValidationError("Instance is required for validation") # Only update is allowed # Validate "must" condition if instance.must and not data.get("done"): raise serializers.ValidationError(f"Checklist item {instance.id} is required but not completed.") # Validate that value is a number if instance.check_type == WorksheetChecklistItem.CheckType.VALUE and not isinstance(data.get("value"), (int, float)): raise serializers.ValidationError(f"Checklist item {instance.id} requires a numeric value.") return data So I'm relying on the default ListSerializer class that is triggered when the serializer is instantiated with the many=True argument. My validation fails because the validate method does not have an "instance" argument like the update method … -
Django: querying two ManyToMany fields on the same model
Given the following models: class Color(models.Model): name = models.CharField() class Child(models.Model): fave_colors = models.ManyToManyField(Color) tshirt_colors = models.ManyToManyField(Color) How would I construct a query to find children who own t-shirts that are their favorite colors? i.e. lucky_kids = Child.objects.filter( fave_colors__exact=tshirt_colors ) # obvious but not valid query -
Using pytest and mongoengine, data is created in the main database instead of a test one
I've installed these packages: python -m pip install pytest pytest-django And created a fixture: # core/services/tests/fixtures/checkout.py import pytest from bson import ObjectId from datetime import datetime from core.models.src.checkout import Checkout @pytest.fixture(scope="session") def checkout(mongo_db): checkout = Checkout( user_id=59, amount=35_641, ) checkout.save() return checkout and imported it in the conftest.py in the same directory: # core/service/tests/conftest.py from core.service.tests.fixtures.checkout import * Here's how I connect to the test database: # conftest.py import pytest from mongoengine import connect, disconnect, connection @pytest.fixture(scope="session", autouse=True) def mongo_db(): connect( db="db", name="testdb", alias="test_db", host="mongodb://localhost:27017/", serverSelectionTimeoutMS=5000, ) connection._connections.clear() yield disconnect() And this is my actual test: import json import pytest from core.service.checkout import a_function def test_a_function(checkout): assert checkout.value is False response = a_function(id=checkout.id, value=True) assert response.status_code == 200 response_data = json.loads(response.content.decode("UTF-8")) assert response_data.get("success", None) is True checkout.reload() assert checkout.value is True But every time I run pytest, a new record is created in the main database. How can I fix this to use a test database? -
Stripe subscription intent error for 3 days
I have problem with Stripe Subscription integration into flutter (Back-end is Django) inside Views.py i have class CreateSubscriptionIntentView(APIView): permission_classes = [IsAuthenticated] def post(self, request): try: stripe.api_key = settings.STRIPE_SECRET_KEY price_id = request.data.get('priceId') if not price_id: return Response({'error': 'priceId is required'}, status=400) # Get or create user profile profile = request.user.profile # Create customer if missing if not profile.stripe_customer_id: customer = stripe.Customer.create( email=request.user.email, metadata={'django_user_id': request.user.id} ) profile.stripe_customer_id = customer.id profile.save() # Create subscription with retry logic subscription = None invoice = None payment_intent = None for _ in range(3): # Retry up to 3 times try: # 1. Create subscription subscription = stripe.Subscription.create( customer=profile.stripe_customer_id, items=[{'price': price_id}], payment_behavior='default_incomplete', payment_settings={ 'payment_method_types': ['card'], 'save_default_payment_method': 'on_subscription' } ) # 2. Retrieve invoice with expansion invoice = stripe.Invoice.retrieve( subscription.latest_invoice, expand=['payment_intent'] ) if invoice.payment_intent: payment_intent = invoice.payment_intent break except stripe.error.StripeError: time.sleep(1) # Wait 1 second before retry continue if not payment_intent: return Response({'error': 'Payment intent not available after creation'}, status=500) # Save subscription ID profile.stripe_subscription_id = subscription.id profile.save() return Response({ 'clientSecret': payment_intent.client_secret, 'subscriptionId': subscription.id }) except Exception as e: return Response({'error': str(e)}, status=500) Inside Flutter page called final_payment_screen.dart i have Future<void> _initSheet() async { setState(() { _loading = true; _error = null; }); try { // Pick your … -
Function to Password recovery email only works on localhost in django
I have the code below that is responsible for sending a password recovery email to the user who made the request. However, it only works on localhost if they access nginx using my machine's IP or access the VPS with the application deployment does not work. the link is generated normally regardless of the url, however the email is only generated outside of localhost if I remove the reset link I need the email to be sent regardless of the host, follow the code: def password_reset_request(request): if request.method == "POST": form = PasswordResetRequestForm(request.POST) if form.is_valid(): cpf = form.cleaned_data['cpf'] # Get user by CPF user = CustomUser.objects.get(cpf=cpf) # Adjust field as needed # Generate password reset token token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) # Create password reset link reset_link = request.build_absolute_uri( reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token}) ) # Prepare email theme = 'Reset Password' email_template = 'auth/recovery_email.html' email_context = { 'user': user, 'reset_link': reset_link, 'valid_hours': 24 # Token validity in hours } email_content = render_to_string(email_template, email_context) try: # Send email send_mail( theme, '', # Plain text version (empty as we're using HTML) settings.DEFAULT_FROM_EMAIL, [user.email], html_message=email_content, fail_silently=False, ) print("Email sent successfully!") except Exception as e: print(f"Email sending failed: {e}") print(f"Email sending failed: … -
How to re-enter fullscreen after first exit and auto-submit form on second exit (anti-cheating JavaScript logic)
I'm building an online exam system in Django and want to implement anti-cheating logic using JavaScript fullscreen detection. Goal: On first exit from fullscreen: ➤ Show a warning: "Warning: Exited fullscreen mode. (1/2)" ➤ Automatically re-enter fullscreen after a short delay. On second exit from fullscreen (or other cheat triggers): ➤ Immediately submit the exam form. No second warning. What I’ve done: I’m using JavaScript to detect: fullscreenchange visibilitychange (tab switch) blur (focus lost) Here’s the relevant JavaScript: let cheatCount = 0; const maxAllowedCheats = 2; let submitted = false; let lastCheatTime = 0; const CHEAT_COOLDOWN = 1500; let warnedFullscreenOnce = false; function handleCheatAttempt(reason, force = false) { const now = Date.now(); if (!force && now - lastCheatTime < CHEAT_COOLDOWN) return; lastCheatTime = now; cheatCount++; if (cheatCount < maxAllowedCheats) { alert(`Warning: ${reason}. (${cheatCount}/${maxAllowedCheats})`); // Try to re-enter fullscreen only on first "Exited fullscreen mode" if (reason === "Exited fullscreen mode" && !warnedFullscreenOnce) { warnedFullscreenOnce = true; setTimeout(() => goFullscreen(), 500); } } if (cheatCount >= maxAllowedCheats && !submitted) { submitted = true; alert("Cheating detected. Submitting your test."); document.getElementById("exam-form").submit(); } } function checkFullscreen() { const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; if (!isFullscreen) { if (!warnedFullscreenOnce) { handleCheatAttempt("Exited … -
Any way to improve my fitness services app?
I'm still a somewhat beginner when it comes to coding (I have been slowly learning it in my own time and think I've gotten pretty good) but would greatly appreciate any feedback on my form functionality specifically, as that's what I have been trying to get down recently. I'd love to know if there is anything I can do to improve my code at all from optimisation to professionalism. Thanks. forms.py class ConsultationForm(forms.ModelForm): class Meta: model = Consultation fields = ['address_line_1', 'address_line_2', 'postcode', 'description', 'date'] widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), 'description': forms.Textarea(attrs={'rows': 4}) } class SessionForm(forms.ModelForm): consultation = forms.ModelChoiceField( queryset=Consultation.objects.all(), empty_label="Select a consultation", help_text="Please select a previous consultation", required=True ) class Meta: model = Session fields = ['consultation', 'workout', 'date'] widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), } def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if user: self.fields['consultation'].queryset = Consultation.objects.filter(user=user) class CheckInForm(forms.ModelForm): session = forms.ModelChoiceField( queryset=Session.objects.all(), empty_label="Select an session", help_text="Please select a previous session", required=True ) class Meta: model = CheckIn fields = ['session', 'date'] widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), } def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if user: self.fields['session'].queryset = Session.objects.filter(user=user) views.py @login_required def booking_form(request, service_type): SERVICE_MAP = { 'consultation': {'form': … -
Preserving Document Format in the Frontend using React JS
I am working on a project which is about document manipulation using AI. The frontend is build on React Js and the backend is built on Django. But the problem that i am facing is: When I upload the document and manipulate it in the frontend and then save it using any frontend library, the format is not preserved. The uploading document contains images and tables, but the downloaded document always downloads it as plain text. I changed my approach and created html blob for the file and saved it in docx extensions, but since its mainly masquerading, it corrupts the images that are in the document BUT preserves the format. IF anyone knows the solution to this, please do help. I tried creating its html blob, change the mime type and save it as docx. But it corrupted the images of the document. -
Android OpenAPI generator client can not connect to Django Rest API made with rest framework
I just generated a android client for an schema of a API built by myself and enabled internet connection permission with: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> I copied the code, changed the package name and URLS for api, so that in my client.api.PhotosApi class for example I have: public class PhotosApi { String basePath = "http://10.0.2.2:8000"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { getInvoker().addDefaultHeader(key, value); } And all the code is autgenerated by https://openapi-generator.tech/. This IP and port corresponds to the IP of my local computer because the code is running on an android emulator. Well, when I use the API to retrieve photos for example, I get: 2025-04-22 11:26:50.039 20890-20890 AndroidRuntime es.example.rallyfotografico E FATAL EXCEPTION: main Process: es.example.rallyfotografico, PID: 20890 java.lang.IllegalStateException: Could not execute method for android:onClick at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:472) at android.view.View.performClick(View.java:7448) at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) at android.view.View.performClickInternal(View.java:7425) at android.view.View.access$3600(View.java:810) at android.view.View$PerformClick.run(View.java:28305) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:467) at android.view.View.performClick(View.java:7448) at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1218) at android.view.View.performClickInternal(View.java:7425) at android.view.View.access$3600(View.java:810) at android.view.View$PerformClick.run(View.java:28305) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) Caused by: java.lang.RuntimeException: java.util.concurrent.TimeoutException at es.example.rallyfotografico.LaunchActivity.test(LaunchActivity.java:66) at … -
django celery: object has no attribute 'delay_on_commit'
django 4.2 with celery 5.5.1 launching a celery task from a django view sometimes causes "'generate_report' object has no attribute 'delay_on_commit'" # tasks.py from celery import shared_task @shared_task def generate_report(data): # Code to generate report ... # django view def testview(request): from tasks import generate_report generate_report.delay_on_commit("mytestdata") return render(request, "simple_page.html") This happens on some deployments, but not on all. And when it happens, a server (webapp) reboot solves the issue. Moving the "generate_report" import to the top of the file also did not help. Note: Code is deployed on pythonanywhere.com with several celery workers running in "always on" tasks. -
Django Broken Pipe Error during Form Submission
I am developing an online crime reporting system using django. I have a page which contains a form that helps register the incident. the form is as : {%extends 'BaseTemplate.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {%load static tailwind_tags%} {%tailwind_css%} </head> <body> {% block main_content %} <form action="" method="post" id="register_form" class="max-w-4xl mx-auto bg-white shadow-[0_2px_13px_-6px_rgba(0,0,0,0.4)] sm:p-8 p-6 rounded-md transform duration-500" enctype="multipart/form-data"> {% csrf_token %} <div class="grid sm:grid-cols-2 gap-6 transform duration-500"> <div> <input type="hidden" name="register_crime_form" id="register_crime_form" value="register_crime_form"> <label class="text-gray-900 text-sm mb-2 block">What Type of crime did you witness/face?</label> <select name="crime_type" type="text" required class=" focus:bg-transparent w-full text-sm text-gray-800 px-4 py-2.5 rounded border focus:ring-0 focus:border-black outline-none transition-all" placeholder="Enter name"> <option value="" disabled selected value>-- choose an option --</option> <option value="ANTI_SOCIAL">Antisocial Behaviour</option> <option value="BURGLARY">Burglary</option> <option value="CRIMINAL_DAMAGE">Criminal Damage</option> <option value="CYBER_CRIME">CyberCrime</option> <option value="FRAUD">Fraud</option> <option value="HATE_CRIME">Hate Crime</option> <option value="ROBBERY">Robbery</option> <option value="RURAL_CRIME">Rural Crime</option> <option value="SPIKING">Spiking</option> <option value="STACKING">Stacking</option> </select> </div> <div> <label class="text-gray-900 text-sm mb-2 block">Date of the Crime</label> <input name="crime_date" type="date" required class=" focus:bg-transparent w-full text-sm text-gray-800 px-4 py-2.5 rounded border focus:ring-0 focus:border-black outline-none transition-all" /> </div> <div> <label class="text-gray-900 text-sm mb-2 block">Time of the Crime</label> <input name="crime_time" type="time" required class=" focus:bg-transparent w-full text-sm text-gray-800 px-4 py-2.5 rounded border focus:ring-0 focus:border-black outline-none … -
I want to know if there is a method to show other users' info in Django [closed]
Im new in Django and i find a problem about the admin pages. i have a html page and i want to show all users' info like name and permission. Andi want to add a button that can delete this user or jump to this user's info page in django admin page. how can i do it? -
Django javascript functions running arbitrarily
I have 2 functions in my views.py and javascript. running at intervals of 1 and 10 sec respectively. They share a cumulative df. Although I'm using Lock(), the functions seem to give random outputs. -
Problem in logging out in Postman while sending POST Request through API
I am using POSTMAN to send API Requests.I have been logged in through API and got a token. When I try to log out using that particular token it display output as "not logged in" This is the screenshot of my token I got in Postman: and this is the output I get while sending POST request to log out: I am trying to logout with the same token I logged in with in Django application. Here is my code in Django: def logout_user(request): if request.user.is_authenticated: request.user.auth_token.delete() return Response({'message': 'Successfully logged out'}) else: return Response({'error': 'Not logged in'}, status=status.HTTP_401_UNAUTHORIZED -
Should I add the output.css file of tailwindcss into .gitingnore file?
I am working on a django project and trying tailwindcss for the first time with it. Although i integrated both of them successfully. But i have a doubt should i add the output.css file into the .gitignore file as this file is rebuilding whenenver i am doing some changed inside my project. So will it be okay if i add this 'output.css' file into the .gitignore file. Currently this output.css files resides inside the static directory. -
Django view: Can't import module from another directory
I have a django project structure like so: core_project/ App1/ Views.py Models.py .. App2/ Views.py Models.py .. Python_code/ Object_refresh/ __init.py__ refresh.py config.py Inside views.py I have a view called "run_refresh" that will run refesh.py from python_code. But I run into a problem trying to reference other .py files inside Python_code. In the view I use: from python_code import * But it isn't able to see main.py. If I type out "from python_code import main" it works but then it can't find env_config.py. This is what I have in my view.py: from core_project.python_code.object_refresh import * .. And this is the error: newfeature = asyncio.run(object_refresh.refresh(rows_to_refresh, schema, 'tbl_name')) print(newfeature) Error: newfeature = asyncio.run(object_refresh.refresh(rows_to_refresh, schema, 'tbl_name')) ^^^^^^^^^^^^^^^^^^^ AttributeError: module 'core_project.python_code.object_refresh' has no attribute 'refresh' Maybe i need to setup my init.py a certain way but i'm not sure. Any help is appreciated. -
i have problem activating my env using django with python in vscode
env\Scripts\activate when i want to activate my env they saying i cant cause the execution of the script its disabled and its hapens to me with every file in my django folder (except the html files) i would be glad if someone help me resolving this problem thanks you i want to create a html page using dgango and python (in vs code ) , to do that i need first to solve 2 problems 1- i need to solve the problem of django: they saying me that django is not found even thou i donwload it in my terminal of vs code ç 2- i have problem activating my envirement as u can see in the foto -
Celery raises `ValueError: not enough values to unpack (expected 3, got 0)` when calling task
I'm using Celery in a Django project to schedule notification tasks. When I start the Celery worker and the task runs, I get the following error: ValueError: not enough values to unpack (expected 3, got 0) Full traceback: File "celery\app\trace.py", line 640, in fast_trace_task tasks, accept, hostname = _loc ValueError: not enough values to unpack (expected 3, got 0) This happens when the following task is triggered: # core/tasks.py from celery import shared_task from django.utils import timezone from core.models import Notification @shared_task def send_scheduled_notifications(): now = timezone.now() notifications = Notification.objects.filter( is_read=False, send_at__lte=now ) for notification in notifications: print(f"Sending notification: {notification.title}") notification.is_read = True notification.save() Celery starts successfully and logs the task as received, but then immediately crashes with the error above. My environment: Windows 11 Python 3.13 Celery 5.5.1 Redis running locally I’ve confirmed the task runs fine when executed manually outside Celery. "I came across this similar question, but my error occurs in a different version of Celery and the task seems structured correctly." -
Django paginator page turns to list
I'm trying built a matrimonial site in Django. The following is the code for displaying a single profile at a time. unfiltered_list = profile_matches for profile in unfiltered_list: print("\n profile:",profile,"\n") profiles_list = profile_matches paginator = Paginator(profiles_list,1) page_number = request.GET.get('page', 1) profiles = paginator.page(page_number) profile_id = profiles.object_list.values('user_model_for_profile_id') The code works fine if I remove the for loop, but when I try to loop through the unfiltered list, 'profiles' becomes a list even though I haven't touched it, other than creating a variable that references to it. I get an Attribute error saying AttributeError: 'list' object has no attribute 'values' Is this a problem with Django itself? Or am I missing something? -
How to make authentication in django using rest framework?
I am currently working on a project called “Asset Management System.” I have created five models: AssetCategory, Asset, AssetDetails, AssetOut, and Person. Each of these models contains the following fields: AssetCategory: Name of the category of the asset Asset: Name of the asset AssetDetails: Description of the asset AssetOut: Amount of the asset that has been out of stock Person: Information about the person who owns the asset I have already developed an API for CRUD operations for these models. I am now trying to create an authentication API for my project. I would like to know how I can do this using Rest Framework(using JWT Authentication instead of tokens). Please note that you can update the above model as per your requirements. i have not tried im new to making authentication api. -
Uncaught SyntaxError: Unexpected end of input in Django Template (inline JS)
I'm developing a Django web application to visualize data from uploaded XML files. I'm encountering a persistent Uncaught SyntaxError: Unexpected end of input in the browser console when loading the data visualization page. This error prevents the JavaScript from running and the chart (using Chart.js) from displaying. Problem: When I navigate to the /visualizer/data-visualizer/ page, the browser console shows Uncaught SyntaxError: Unexpected end of input, pointing to a line number within the main HTML response (e.g., data-visualizer/:3149:80). The chart area on the page remains blank. Context: Django Version: 5.2 Python Version: [Your Python version, e.g., 3.9, 3.10] Operating System: Windows Web Server: Django Development Server (manage.py runserver) The application workflow is: Upload XML file -> Select data fields -> View visualization page (/visualizer/data-visualizer/). The visualization page is rendered by the VisualizerInterfaceView using the visualizer_interface.html template. The template includes Chart.js via a CDN and has an inline <script> block containing custom JavaScript logic to retrieve data from JSON embedded in the template and render the chart. Observed Behavior and Debugging Steps Taken: The Uncaught SyntaxError: Unexpected end of input error appears consistently in the browser console (tested in Chrome and Edge). Looking at the browser's "View Page Source" for the /visualizer/data-visualizer/ … -
How should a CLIENT_SECRET for OAuth be accessed?
I have a nextJs SPA and a Django web application. For authentication I am trying to implement OAuth with Google. From the articles I've read related to this I've understood that client_secret shouldn't be stored on the client_side in my case the nextJs app. What confuses me is that when a user tries to login they would need to access the client_secret. lets say I retrieve the client_secret through an API when the user tried to login and then use the retrieved client_secret. Wouldn't it still be exposed to potential malicious parties? What would be a secure way to store and retrieve the stored client_secret? I tried to follow the next-auth tutorial to setup Google OAuth but the client_id and client_secret and both stored on the nextJs application which go against recommendations related to OAuth implementations. -
Django, LoginRequiredMiddleware, login, and media
in a Django 5.2 application I discovered LoginRequiredMiddleware. It's a great system. However, I have some problems with the media. When a url has the @login_not_required() decorator, it's impossible to display uploaded images. in the console, when the page is loaded, django considers this as a next_url. [19/Apr/2025 08:11:34] "GET /media/identity/background.jpg HTTP/1.1" 302 0 [19/Apr/2025 08:11:34] "GET /?next=/media/identity/background.jpg HTTP/1.1" 200 3062 If the user is logged in, it works fine by declaring the images downloaded with MEDIA_URL like the examples below. If the user is anonymous, then the image is in error. <style> body{ background-image: url("{{ MEDIA_URL }}{{ identity.background }}") !important; } </style> <img src="{{ MEDIA_URL }}{{ identity.logo }}" style="width: auto; height: 100px;"> #settings.py # Media files MEDIA_ROOT = BASE_DIR / "media" MEDIA_URL = "/media/" Do you have any idea how to display the media? I've started to make a custom middelware but that's not the point. -
Can find an input value throught its id in a django generated table
I'm very new to javascript and must use it for a project in which i'm using a table and want to extract the value of an input field with id generated trough a Django function. i don't know if that could be relevent but i'm using datatable in this project. The HTML code looks like this: <head> <script src="{% static 'myProject/jQuery/jquery-3.7.1.js' %}"></script> <script src="{% static 'myProject/javaScript/datatables.min.js' %}"></script> <script src="{% static 'myProject/javaScript/checkFunc.js' %}" defer></script> <link rel="stylesheet" href="{% static 'myProject/CSS/checkStyle.css' %}"> <link rel="stylesheet" href="{% static 'myProject/CSS/datatables.min.css' %}"> </head> <table id="myTable"> <thead> <tr> <th>Head Value</th> <th>Another head Value</th> </tr> </thead> <tbody> {% for value in list_of_value %} <tr> <td><input type="number" id="amount{{ value.id }}" value="1"></td> <td><button onclick="check(value.id)">Check input box</button></td> </tr> {% endfor %} </tbody> </table> And the JS like this: function check(value_id){ const amount= document.getElementById("amount"+wallet_id); console.debug(amount); } In the console all i get is "null" as if it doesn't exist but i tried modifying it with CSS and it worked just fine. I also tried using jQuery as so: function check(value_id){ var actionTable = $("#amount" + value_id +""); console.debug(actionTable); console.debug(actionTable.value); } And on this one i don't get a null i get an object: Object { } <prototype>: Object { jquery: "3.7.1", constructor: …