Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting 401 when attempting to signup or login in django allauth react-spa example
I am very new to using to Django-allauth, I'm wanting to integrate it with my Django backend. I was trying to use the react-spa example outlined in the docs https://react.demo.allauth.org/, but I 401 error when sending either a signup or login request. Why is this happening? The response looks like: { "status": 401, "data": { "flows": [ { "id": "login" }, { "id": "login_by_code" }, { "id": "signup" }, { "id": "provider_redirect", "providers": [ "dummy" ] }, { "id": "provider_token", "providers": [ "dummy" ] }, { "id": "mfa_login_webauthn" }, { "id": "verify_email", "is_pending": true } ] }, "meta": { "is_authenticated": false } } I understand that the flows array indicates those are the methods to authenticate. But how can I authenticate if the login / signup method preventing me from doing so? Steps to repro: I ran this example locally, cloned it here https://codeberg.org/allauth/django-allauth/src/branch/main/examples/react-spa Ran docker compose up Visit localhost:10000, when to signup - entered email and password + password confirmation. Request was successful and I was redirected to the enter email confirmation code screen I didn't input the code in step 3. Instead, went back to signup page to enter my actual email to get the code and input … -
Run EXE software using App in Windows IIS
I hosted my Django app on Windows IIS in Windows Server 2022 Standard But my application has a feature that opens software (.exe) and run specific user tasks provided in the request of the site. For example, a user provides some input from my site, and then it processes it with my app by opening software using python code in views.py script_path = "C:\inetpub\wwwroot\webapp\script\runthescript.py" subprocess.run(["C:/Program Files/My Soft/Soft.exe", "-runScriptFile", script_path]) MY PROBLEM When I tested my application locally using python manage.py runserver it was working due to admin privileges and session 1 access, but the same when I tried after hosting with IIS then everything working except software to start. WHAT I TRIED: I tried providing my AppPool Identity as (IIS APPPOOL\webapp) Administrator privileges. Tried using Task Scheduler, but it works with the background process but not with the GUI app. ISSUE When I googled it, I found that it is due to privileges and session 0 access. IIS has only session 0 isolation so that it is unable to access GUI. Your small help, idea or suggestion definitely be helpful for me. :) -
Pass value from one Django template to other
I want to build a Django template hierarchy like so: root.html |_ root-dashboard.html |_ root-regular.html root.html shall have an if statement: {% if style == "dashboard" %} {# render some elements in a certain way #} {% else %} {# render those elements in a different way #} {% endif %} And root-dashboard.html and root-regular.html should individually extend root.html by setting style: # root-dashboard.html {% extend 'root.html' with style='dashboard'%} # root-regular.html {% extend 'root.html' with style='regular'%} (with above is not an actual valid syntax, its just something similar I want) And a view can use either root-dashboard.html or root-regular.html to show the content in one style or the other. How do I achieve this without the view having to set the style context? -
How to handle authentication and AUTH_USER_MODEL in Django multi-tenant with separate databases?
I’m developing a multi-tenant SaaS application using Django, where each tenant has its own separate database with its own schema and relationships. However, I'm struggling with how to properly manage authentication and define AUTH_USER_MODEL in this environment. 📌 System Requirements Global superadmins that manage the system and are stored in the public database (public). Tenant users, who exist in their respective tenant database and have relationships with other tables inside their own database. Separate authentication: Superadmins should authenticate in the public database. Tenant users should authenticate within their specific tenant database. The main problem is that Django allows only one AUTH_USER_MODEL, but I need to manage users separately for each tenant while maintaining the ability to associate them with other tables within their respective databases. ❌ Current Issue If I define a single user model in AUTH_USER_MODEL, I cannot differentiate between global superadmins and tenant users, nor can I correctly manage relationships within each database. I tried defining two different user models, but Django does not allow multiple AUTH_USER_MODEL, which complicates authentication. ✅ Possible Solution I thought of defining a base model BaseUser that extends AbstractUser, and then creating two inherited models. But I am not sure which is the … -
I am trying to run uwsg-emporer vassal and it can't find my python
When I create a uwsgi vassal ini file, the server throws this error when I hit the site: --- no python application found, check your startup logs for errors --- The virtualenv is correct and if I do python manage.py check I do not have errors and python manage.py runserver runs a dev version fine. I first source in my venv so I know python is installed in the Virtual Envelope at this path: /var/www/webapps/lhhs/env this is my .ini file [uwsgi] uid = www-data socket = /var/www/webapps/lhhs/lhhs.sock chown-socket = %(uid):www-data chmod-socket = 660 chdir = /var/www/webapps/lhhs/ virtualenv = /var/www/webapps/lhhs/env binary-path = /var/www/webapps/lhhs/env/bin/uwsgi modue = lhhs.wsgi:application wsgi-file = lhhs/wsgi.py env = DJANGO_SETTINGS_MODULE=lhhs.settings.dev module = django.core.handlers.wsgi:WSGIHandler() stats = 127.0.0.1:9191 vacuum = true processes = 1 threads = 1 plugins = python3,logfile logger = file:/var/www/webapps/lhhs/log/uwsgi.log -
request.method == POST equaling true in next function causing it to run prematurely
so i am running this code def login_or_join(request): if request.method == "POST": option = request.POST.get("option") print('post request recieved') if option == "1": return login_screen(request) if option == '2': return in_game(request) return render(request,"login_or_join.html") and def login_screen() looks like this def login_screen(request): if request.method == "POST": username = request.POST.get("username") password = request.POSt.get("password") print(username) print(password) user = authenticate(request, username=username, password=password) print(user) if user is not None: return redirect('join_lobby') else: return render('login_page.html', {'error': 'Invalid login credentials' }) return render(request, 'login_page.html') Whenever I click "option 1" it runs login_screen but in a way I don't want it to. it seems to just follow that request.method == "POST" and prints username and password immediately, meaning it is setting username and password immediately making any log in attempt wrong. But I don't want it to set those (or print them) until I've pressed the button on the next page. Further more when I hit "enter" or "log in" it doesn't reshow the page with the error message, it just goes back login_or_join(). I feel like I am taking crazy pills as I've been working on this website for a while and this is the first time I'm having this kind of issue. I've tried messing with it … -
Django syntax highlighting/intellisense not working for undefined class methods
I'm working in a python/django repo and I'm having an issue where unknown methods are not being highlighted by VSCode with a red error squiggly line. As you can see from the screenshot, I have it setup to show python errors, but the non-existent method on the test_email class doesn't throw any errors or warnings. I have Black Formatter, isort, Pylance, Python, Pylint, Python Debugger extensions installed. The correct python interpreter + environment are setup and the python language server is also running. I'm happy to include any other information, but didn't want to dump unneeded info. Any insight, help or guidance is greatly appreciated! -
I am confused....whether Mern is better or django....and which is more in use in companies? [closed]
please tell me which one is better MERN or Django and what is more prefferd in companies these days? -
Raspberry Pi based POS: what do you think?
I have finished a simple but hopefully complete and useful Order Management and POS System built on a RaspBerry Pi based on Django and a Apache web server. I know it is perhaps too ambitious to call it "POS", given its simplicity. Anyhow, please feel free to take a look and provide your feedbacks: https://github.com/simOrderS/simOrder -
Account creation and authentication using Django
I'm hitting a wall with this code. I am able to create a user and store the data. I can see the user in django admin panel. When I try logging into that user, I get a failure message. Ive tried changing the password in the django-admin panel. That did not work either. Here is my code. login.html {% extends "users/base.html" %} {% block title %} Login Page {% endblock title %} {% block content %} <div class="container"> <div class="row justify-content-center align-items-center" style="min-height: 100vh;"> <div class="col-lg-5"> <div class="card shadow-lg border-0 rounded-lg"> <div class="card-body"> <h3 class="font-weight-light my-1 text-center">Sign In</h3> {% if form.errors %} <div class="alert alert-danger alert-dismissible" role="alert"> <div id="form_errors"> {% for key, value in form.errors.items %} <strong>{{ value }}</strong> {% endfor %} </div> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> <label class="small mb-1">Username</label> {{ form.username }} </div> </div> </div> <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> <label class="small mb-1">Password</label> {{ form.password }} </div> </div> </div> <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> {{ form.remember_me }} <label> Remember me</label> </div> </div> </div> <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group mt-0 mb-1"> <button name="login" class="col-md-12 … -
How to Enable Web Push Notification Permissions on iOS for a Django Web App?
I am building a Django web app for status checking and need real-time background updates using the Web Push API. The web app will be accessed on both Android and iOS devices. To enable push notifications, I am using the Notification API to request user permission. The implementation works on Windows, Linux, Android, and Mac, but it does not work on iOS. However, I do not want to convert my web app into a Progressive Web App (PWA). I need guidance on how to request notification permissions on iOS and ensure web push notifications function correctly. Can someone help me find a solution to complete my project? Current Implementation I am using the following JavaScript code to request notification permissions from users: document.getElementById('grant-permission').addEventListener('click', ()=> { Notification.requestPermission().then(permission => { console.log("permission:", permission); if (permission === "granted") { console.log("Notifications allowed!"); } else { console.log("Notifications denied!"); } }); }); Issue This code works as expected on Windows, Linux, Android, and Mac. However, on iOS (Safari), it does not work. The permission prompt does not appear, and notifications are not allowed. What I Have Tried Tested on different browsers (Safari, Chrome) on iOS. Confirmed that Web Push API only works for installed PWAs on iOS. … -
I've been working on buildings a password reset system on my django site
I intend on also using a similar system for account creation confirmation but i am unable to test the system at the moment as i am having issues with my mailgun account def password_reset_request(request): if request.method == 'POST': email = request.POST.get('email') try: user = get_user_model().objects.get(email=email) # Generate reset token and expiry profile, created = UserProfile.objects.get_or_create(user=user) profile.generate_reset_token() # Prepare the email context with the reset token context = { 'user': user, 'reset_token': profile.reset_token, # Send the reset token in the email } # Render email templates email_html = render_to_string('password_reset_email.html', context) email_plain = strip_tags(email_html) # Mailgun API setup mailgun_url = f"https://api.mailgun.net/v4/{MAILGUN_DOMAIN_NAME}/messages" mailgun_auth = ("api", MAILGUN_API_KEY) mailgun_data = { "from":DEFAULT_FROM_EMAIL, "to": user.email, "subject": "Password Reset Request", "text": email_plain, "html": email_html } # Send email via Mailgun API try: response = requests.post(mailgun_url, auth=mailgun_auth, data=mailgun_data, verify=False) if response.status_code == 200: messages.success(request, "A password reset token has been sent to your email.") else: messages.warning(request, "Password reset requested, but there was an issue sending the email.") except requests.exceptions.RequestException as e: messages.warning(request, f"Password reset requested, but we couldn't send the email: {str(e)}") return redirect('password_reset_verify') except get_user_model().DoesNotExist: messages.error(request, "Email address not found.") return render(request, 'password_reset_request.html') def password_reset_verify(request): if request.method == 'POST': token = request.POST.get('token') # Assuming the user inputs … -
Error: { "detail": "Authentication credentials were not provided." }
Hello community enter image description here I have a problem: When i want to get into information in postman, This sends me the next error: "detail": "Authentication credentials were not provided." Attach: The code in Django Settings.py in (A) that shows the REST_FRAMEWORK REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'authentication.customJWTAuthentication.CustomJWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } Views.py in (B1 and B2) that indicates the code POST from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework import status from roles.models import Role from roles.serializers import RoleSerializer from users.models import User, UserHasRoles from users.serializers import UserSerializer import bcrypt from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import AllowAny from django.conf import settings` Create your views here. GET -> OBTENER POST -> CREAR PUT -> ACTUALIZAR DELETE -> BORRAR 200 RESPUESTAS EXITOSAS 400 O 500 ERRORES` @api_view(['POST']) @permission_classes([AllowAny]) def register(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() client_role = get_object_or_404(Role, id='CLIENT') UserHasRoles.objects.create(id_user=user, id_rol=client_role) roles = Role.objects.filter(userhasroles__id_user=user) roles_serializer = RoleSerializer(roles, many=True) response_data = { **serializer.data, 'roles': roles_serializer.data } return Response(response_data, status=status.HTTP_201_CREATED) error_messages = [] for field, errors in serializer.errors.items(): for error in errors: error_messages.append(f"{field}: {error}") error_response = { "message": error_messages, "statusCode": status.HTTP_400_BAD_REQUEST } return Response(error_response, status=status.HTTP_400_BAD_REQUEST) def getCustomTokenForUser(user): refresh_token = … -
Django ignores urlpatterns
I have created a very basic urlpattern but it is ignored. def hallo(request): return JsonResponse("Hallo", safe=False) urlpatterns = [ # path('admin/', admin.site.urls), # path('admin/', JsonResponse("Hallo", safe=False) ), path("", hallo), path("hallo/", hallo) ] It will always be shown the "standard" page instead of "hallo", and even the admin page. And the page hallo cannot be found. I stopped the server and run it with different ports but there is always the same behaviour. -
I keep getting this issue Invalid block tag on line 5: 'static', expected 'endblock'. Did you forget to register or load this tag?
<!-- about.html --> 1 {% extends 'book/base.html' %} 2 3 {% block title %} About {% endblock %} 4 {% block extra_head %} 5 <link rel="stylesheet" href="{% static 'css/style.css' %}"> 6 {% endblock %} 7 {% block header %} 8 <h1> About Me </h1> 9 {% endblock %} 10 {% block main %} 11 <article> 12 <section> <p>My name is Uyiosasere Idemudia Oduware</p> 13 </section> 14 </article> 15 {% endblock %} base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %} Uyi's Page {% endblock %}</title> {% block extra_head %} {% endblock %} </head> <body> <header> {% block header %} {% endblock %} </header> <main> {% block main %} {% endblock %} </main> <footer> {% block footer %} {% endblock %} </footer> </body> </html> my css file is inside LearnSphere/book/static/css/style.css the base.html and about.html file is inside Learnsphere/book/templates/book/base.html about.html -
django mongo db conection - All auth - Social account extra field error
raise ValueError( ValueError: Cannot alter field socialaccount.SocialAccount.extra_data into socialaccount.SocialAccount.extra_data - they do not properly define db_type (are you using a badly-written custom field?) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) address = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to='account/profilepicture/', blank=True, null=True) mobile_number = models.CharField(max_length=15, blank=True, null=True) def __str__(self): return f"{self.user.username}'s Profile" -
Can't run Pycharm Debugger using WSL2
I have a project that has in PostgreSQL, Celery, Redis, RabbitMQ via docker containers. I'm facing an issue with PyCharm's debugger when running a DRF project in WSL2(Ubuntu). The project runs success in normal mode, but when I start the debugger, it hangs and eventually fails with "Handshake failed" errors in the logs. The full command executed is: /home/myuser/myproject/venv/bin/python3.11 /home/myuser/.pycharm_helpers/pydev/pydevd.py --multiprocess --qt-support=auto --port 29781 --file /home/myuser/myproject/manage.py runserver 8000 Here’s a snippet of the PyCharm logs: 025-03-06 12:48:04,336 [6128385] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,337 [6128386] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,337 [6128386] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,338 [6128387] WARN - #c.j.p.PythonHelpersLocator - Helpers pro root does not exist C:\Users\user\AppData\Local\Programs\PyCharm Professional\plugins\python-ce\helpers-pro 2025-03-06 12:48:04,454 [6128503] INFO - #c.i.e.wsl - WSL mount root for Ubuntu is /mnt/ (done in 114 ms) 2025-03-06 12:48:04,493 [6128542] WARN - #c.i.u.Alarm - Do not create alarm without coroutineScope: com.intellij.ui.GotItTooltip.(GotItTooltip.kt:94) 2025-03-06 12:48:04,508 [6128557] INFO - #c.i.u.WinFocusStealer - Foreground lock timeout set to 0 2025-03-06 12:48:06,295 [6130344] WARN - #c.j.p.d.p.t.ClientModeDebuggerTransport - [92734501] Handshake failed 2025-03-06 12:48:11,303 [6135352] WARN - #c.j.p.d.p.t.ClientModeDebuggerTransport - [1988656345] Handshake failed … -
Why is Django not using the specified cache backend?
As a simple test, I'm attempting to set the cache backend used by Django to something other than the default django.core.cache.backends.locmem.LocMemCache. I'm using a custom backend defined in the django-bmemcached package, which uses the python-binary-memcached module to access a Memcached instance with authentication. I've set the backend in the settings.py file, with the relevant snippet below: CACHES = { 'default': { 'BACKEND': 'django_bmemcached.memcached.BMemcached', 'LOCATION': <ip>:<port>, 'OPTIONS': { 'username': <username>, 'password': <password>, } }, } The settings.py file is being used by the application, but the default cache being used is not the specified cache backend: >>> from django.conf import settings >>> print(settings.CACHES) {'default': {'BACKEND': 'django_bmemcached.memcached.BMemcached', 'LOCATION': <ip>:<port>, 'OPTIONS': {'username': <username>, 'password': <password>}}} >>> from django.core.cache import caches >>> print(caches['default']) <django.core.cache.backends.locmem.LocMemCache object at 0x73bf66531720> This isn't caused by a third party package overriding the cache backend, and the Memcached instance can be accessed and operations performed successfully if a client for the backend is instantiated: bmemcached.Client(<ip>:<port>, <username>, <password>). Using a different binding, such as pymemcache, and setting the backend to a Django supported django.core.cache.backends.memcached.PyMemcacheCache still results in the above issues described where the default cache being used is not the specified cache backend. If at all possible, I'd like to be … -
How to Conditionally Render Mobile and Desktop Ads in Django to Prevent JavaScript Overlap?
I'm working on a Django project where I need to display different ads for mobile and desktop users. Currently, both mobile and desktop ad JavaScript is being loaded, which causes conflicts as the mobile ad scripts interfere with the desktop ads. Here's a simplified version of my template code: <div class="ads-mobile"> {% ad_simple_tag "mobile_ads" %} </div> <div class="ads-desktop"> {% ad_simple_tag "desktop_ads" %} </div> I'm using Cloudflare, which caches the pages, so I can't rely on server-side logic (like middleware) to determine which ads to display, as the result would be cached. I attempted to use JavaScript and/or css to detect the device type and hide/show or remove the ad blocks accordingly, but both ad scripts are still being loaded, causing issues. How can I ensure that only the relevant ad scripts are loaded based on the user's device type, considering that the page is cached by Cloudflare? Is there a client-side approach or best practice for handling this kind of situation in Django? -
How to apply Apache BasicAuth with IP-based access control for django project
I have a Django application and I am using Apache to manage access control. I want to restrict access to django project with this logic -> Allow access only from specific IP addresses. If the request comes from an IP address outside the allowed list, users should be prompted to authenticate using username and password defined in .htpasswd Apache .htpasswd username:encryptedpassword Apache virtual Host <VirtualHost *:80> LoadModule wsgi_module "/var/www/example.com/venv/lib/python3.10/site-packages/mod_wsgi/server/mod_wsgi-py310.cpython-310-x86_64-linux-gnu.so" DocumentRoot /var/www/example.com ServerName example.com WSGIDaemonProcess myapp python-home=/var/www/example.com/venv python-path=/var/www/example.com:/var/www/example.com/venv/lib/python3.10/site-packages WSGIScriptAlias / /var/www/example.com/example/wsgi.py process-group=myapp <Directory "/var/www/example.com/"> AllowOverride All Require all granted <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /var/www/example.com/static/ <Directory /var/www/example.com/static/> Require all granted </Directory> <Directory /var/www/example.com/> AllowOverride All Require all granted </Directory> <Location /> AuthType Basic AuthName "Restricted Access" AuthUserFile /var/www/example.com/.htpasswd Require valid-user <RequireAny> Require ip x.x.x.x Require ip x.x.x.x Require valid-user </RequireAny> </Location> </VirtualHost> Desired behaviour Users accessing any URL in the application from allowed IP addresses should have unrestricted access. Users from non-allowed IP addresses should be prompted for authentication via apache(.htpasswd) Problem is If I am inputing username and password prompted by apache, django gives { "detail": "Invalid username/password." } I dont want to remove headers at apache level because some of my url requires authentication implemented … -
Django images not loading after setting `DEBUG = False` on PythonAnywhere
I have deployed my Django project on PythonAnywhere, and everything was working fine when DEBUG = True. However, after setting DEBUG = False, none of my images (media files) are loading. What I Tried: I have set up MEDIA_URL and MEDIA_ROOT correctly in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I also ran python manage.py collectstatic --noinput and my static files are loading correctly. The images are uploaded and exist in the /home/myusername/django_ecom_web/ecomprj/media/ directory. I checked the file paths in the browser and they return a 404 Not Found error. How I Fixed It: After some research, I found that Django does not serve media files in production when DEBUG = False. To fix this in PythonAnywhere, I had to: Go to Dashboard → Web → Static Files section. Add the following mapping: /media/ → /home/myusername/django_ecom_web/ecomprj/media/ Reload my web app. After doing this, my images started loading correctly. My Question: Why does Django not serve media files in production when DEBUG = False? Is setting up a manual media mapping the only way to serve media files on PythonAnywhere, or is there a better approach? -
Django returns old form data in HTMX response
I changed UpdateView do that it can handle create requests as well if pk=0: class ObjectView(UpdateView): hx_url = "" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) self.hx_url = f"{self.model._meta.app_label}:{self.model._meta.model_name}" context["hx_url"] = reverse( self.hx_url, args=[self.object.id if self.object else 0] ) return context def get_object(self, queryset=None): if self.kwargs.get(self.pk_url_kwarg) == 0: return None return super().get_object(queryset) def form_invalid(self, form): messages.add_message( self.request, messages.ERROR, "Invalid input.", ) return self.render_to_response(self.get_context_data(form=form)) def form_valid(self, form): messages.add_message( self.request, messages.SUCCESS, "Data saved.", ) if self.request.htmx: return self.render_to_response(self.get_context_data(form=form)) return redirect(self.object.get_absolute_url()) In my View I am checking if price field was updated and if yes update the price_date field as well: class PartView(ObjectView): model = Part form_class = PartForm def form_valid(self, form): if self.object: old = Part.objects.get(id=self.object.id) old_price = old.price self.object = form.save(commit=False) if self.object.price != old_price: self.object.price_date = date.today() self.object.save() form.save_m2m() else: self.object = form.save() return super().form_valid(form) I make an htmx call to it from my template: <div id="modalContent" hx-target="this"> <form method="post" hx-post="{{ hx_url }}" hx-on:htmx:validation:failed="this.reportValidity()" hx-trigger="click from:#btn-save"> {% csrf_token %} <div> {% include "form_field.html" with form_field=form.price %} {% include "form_field.html" with form_field=form.price_date %} </div> </div> </form> {% include "btn_save.html" %} {% include "messages.html" %} </div> The problem is even though it successfully updates the price_date in the DB it still … -
Django ModuleNotFoundError: No module named 'ecomprj' on PythonAnywhere Deployment
Body: I am deploying my Django project on PythonAnywhere, but I keep getting this error in my logs: ModuleNotFoundError: No module named 'ecomprj' Project Structure: My Django project is located at: /home/Sagarmoy007/django_ecom_web/ecomprj/ Running ls -l /home/Sagarmoy007/django_ecom_web/ecomprj gives: __pycache__ core customercare db.sqlite3 deladmin ecomprj errorriders locustfile.py manage.py media migrate.bat notification_app others requirements.txt returnadmin staffdata static staticfiles templates useradmin userauths vendorpannel videoshareing whoosh_index Inside /home/Sagarmoy007/django_ecom_web/ecomprj/ecomprj/, I have: __init__.py settings.py urls.py wsgi.py asgi.py My WSGI File (/var/www/sagarmoy007_pythonanywhere_com_wsgi.py): import os import sys # Add the correct project paths sys.path.append('/home/Sagarmoy007/django_ecom_web/ecomprj') # The main directory sys.path.append('/home/Sagarmoy007/django_ecom_web/ecomprj/ecomprj') # The Django project folder # Set Django settings module os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ecomprj.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() What I Have Tried: Verified that manage.py exists inside /home/Sagarmoy007/django_ecom_web/ecomprj. Checked that the Django settings module is correctly set (ecomprj.settings). Restarted the web app from the PythonAnywhere dashboard. Ran python manage.py shell inside /home/Sagarmoy007/django_ecom_web/ecomprj, but it fails with the same ModuleNotFoundError. Questions: Is my WSGI configuration correct? Do I need to modify my PythonAnywhere environment? How can I properly set up Django on PythonAnywhere to recognize my project? -
How to replace super().save() in MyCustomSignupForm when recaptcha is not confirmed
How to replace super().save() in MyCustomSignupForm when recaptcha is not confirmed class MyCustomSignupForm(SignupForm): def save(self, request): token = request.POST['g-recaptcha-response'] action = "signup" r_result = recaptcha(request, token, action) if r_result: user = super(MyCustomSignupForm, self).save(request) else: messages.warning(request, '...robot...') user = ??? return user -
Cannot resolve keyword 'mem_ev' into field in Django
I have a small Django project that consists of 2 models (Event, mem_ev) plus auth User and Profile such that Users --< mem_ev >-- Events (ie a classic many to many relationship between Users & Events). I want to be able to list all events for a member and all members for an event both of which entail a join between the main dataset and mem_ev. I have the list of events attended by a member working fine (list_member_events) but cannot get a list of members attending an event (list_event_members) working. My models.py is: from django.db import models from django.utils.text import slugify from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Delete profile when user is deleted event_count = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' #show how we want it to be displayed class Event(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50,default="", null=False) description = models.TextField() cost = models.DecimalField(max_digits = 5, decimal_places = 2, default = 0.0) event_date = models.DateTimeField(null=True,blank=True) attendees = models.IntegerField(default=0) class Meta: ordering = ['event_date'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Event, self).save(*args, **kwargs) class Meta: ordering = ['event_date'] def __str__(self): return self.title class mem_ev(models.Model): member_id = models.ForeignKey("Profile",on_delete=models.CASCADE) event_id = models.ForeignKey("Event",on_delete=models.CASCADE) amt_paid = models.DecimalField(max_digits = …