Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django send just an alter in response instead of a full template
How can I send just an alert message in response to a request instead of having to send a template made just for the alert? I am using Javascript async call. I only need the alert html response to render an InnerHTML. View @login_required(login_url="/login/") @csrf_protect def usersave(request): msg = messages.add_message(request, messages.WARNING, "This is a demo. First complete all info to save.") return render(request, msg) # Want to send just msg instead of a template for an alert. -
Django modal window
I have a modal window for deleting comments. It looks like this: <div id="deleteModal" class="modal"> <div class="modal-content"> <img class="modal-image" src="{% static 'img/icon-modal-delete.png' %}" alt="DELETE"> <h1 class="modal-title">Delete comment?</h1> <div class="modal-block"> <form method="POST"> {% csrf_token %} <button class="modal-sucsess" type="submit">Delete</button> </form> <a class="modal-cancel" onclick="closeModal()">Cancel</a> </div> </div> </div> I include it with the include tag in the django template. There is also a js script for opening and closing the modal window, which looks like this: function openModal() { var modal = document.querySelector('.modal'); modal.style.display = 'block'; } function closeModal() { var modal = document.querySelector('.modal'); modal.style.display = 'none'; } In the django template I have a cycle where I display comments to the publication and each comment has a delete button, which on click calls a modal window, it looks like this: <a class="main-row-content-comments-users-info-delete" onclick="openModal()" >Delete</a> I wrote a view to delete a comment, but it needs to pass the comment id. If I were doing this directly via a link in a template tag, I would simply pass comment.pk, but how do I pass the key to the modal so that when I click the delete button in the modal, the delete view is called? I tried to solve this using Ajax requests, but … -
Lightsail deployment logging; Invalid HTTP_HOST header:You may need to add '****' to ALLOWED_HOSTS
I am deploying a containerised application on Lightsail and whilst the deployment itself is successful, logging shows hundreds of these messages from the same ip address, my assumption is this is some sort of automated process that's failing. I have set the allowed_hosts to just the Lightsail generated url (w/o https//.com etc.) and so I have no idea where this extra ip is coming from. I can't find anything which says I need to have an extra ip on allowed_hosts. Tried to deploy containerised application to Lightsail -
Cannot display image with JavaScript from Django Base
I am attempting to get a customer logo to load when a user signs into my app. To do that I am using the views function below to generate the logo url: Views: def view_company_logo(request): print("GETTING LOGO") client = Client.objects.get(user=request.user) logo = "" try: logo = client.customer.first().logo.logo.url print("GOT LOGO") return JsonResponse({"logo": logo, "media_url": settings.MEDIA_URL}, safe=False) except Exception as e: print(e) print(f'ERROR FOR LOGO {e}') return JsonResponse({"logo": logo}, safe=False) The function is attached the url below: url(r"^get/company_logo/$", views.view_company_logo), This is called in the base.html file in order to show the $(document).ready(function () { document.getElementById("logo").src = get_company_logo(); function get_company_logo() { log('TEST'); $.ajax({ url: '/get/company_logo/', method: 'GET', success: function (data) { console.log(data); console.log(data['logo']); return data.logo }, error: function () { console.log('HERE IS THE ERROR!!!') log('HERE IS THE ERROR!!!') }, }) } Which connects to the source of this image that gets generated when the pages loads: <img class="img-square center" id="logo" alt="logo" style="opacity: 1" height="45" width="125"> Could someone tell me why the image is not loading? It seems like the function is never called and I am not sure why. -
Problem with authentication of login in Django
When trying to authenticate a user using the "authenticate" method, it won't let me log in. I don't know if it is because the authentication method no longer works in new versions of django, or if another method is used. I'm new to django, so I'm just learning: def signin(request): if request.method == 'GET': return render(request, 'signin.html', { 'form': AuthenticationForm }) else: # POST user = authenticate(request, username=request.POST['username'],password=request.POST['password']) if user is None: return render(request, 'signin.html', { 'form': AuthenticationForm, 'error': 'Username or password is incorrect' }) else: login(request, user) return redirect('tasks') In the login template, the indicated method is POST, so that is not the problem there.I tried to change the login name to avoid any conflict, and it was not resolved. -
Count by Month in Django Query
Good afternoon, I am struggling with a query. Ultimately, I have some records I want to query and get a count by month. Ultimately, my goal is to come up with a data set that looks like: Month, opened, closed Jan, 2, 3 Feb, 1, 5 Etc... for the past six months. I have been using this as a base: Django: Query Group By Month This works to get each individually: six_months_ago = datetime.now() - timedelta(days = 180) open_six_months = (Rec.objects .annotate(open=Month('open_date')) .values('open') .annotate(rec_opened=Count('status', filter=Q(status__is_open=True))) .order_by()) closed_six_months = (Rec.objects .annotate(closed=Month('close_date')) .values('closed') .annotate(rec_closed=Count('status', filter=Q(status__is_open=False) and Q(close_date__isnull=False) )) .order_by()) Not all records have a closed date yet. This returns the right data when testing, but its in two different queries. I'd like to have one single data set if possible. Is there an easy way to combine this into one query that has a single row with both the count of the open date and the count of the closed date by month? Thank you for your help. BCBB -
Why can't I save the Django FileField with a null value
I want to use a POST request to create an object with file fields. At the same time, at the model level, I declared that fields can be null. But Django does not allow me to save this object with empty values in the file fields. At the same time, through Django admin, I can create an object with without specifying a file. Error: ValueError: The 'image_before' attribute has no file associated with it. What could this be related to? My request: { "type": "Type", "question": "Text", "category": [ 1 ] } My model: class Question(models.Model): class Meta: db_table = 'questions' question_type = models.CharField( max_length=300, ) category = models.ManyToManyField( Category, ) question_text = models.CharField( max_length=300, ) image_before = models.ImageField( upload_to='media/', null=True, blank=True, default=None, ) correct_answer= models.CharField( max_length=300, blank=True ) I tried to redefine save() and change the value of the field to None there. Then the value of the field will be <FileField: None> -
Mutliple JWT generation with different django secrets based on subdomains
I am using simple JWT (django-rest-framework-simplejwt). I have an auth server which authenticates users. Each user can belong to a single or multiple Tenants and each tenant is represented by a subdomain. I am trying to generate django secret for each tenant and when the tenant docker launches it uses the django secret generated by the auth server(i store it in .tenant1.local.env for tenant one) So when a user tries to connect to a domain, system will create auth token using the secret generated for that tenant. Since that tenant will have an access to .tenant.local.env (same secret that was used to generate the token for that tenant) it ll be able authenticate the users using the secret. The issue is I can not find a simple way to inherit or overwrite a class in django-rest-framework-simplejwt so that I can specify the secret to use to create the token. There is APISettings(which you specify which secrets to use) in the package but there is no example of how to use it. IS there a way to specify which secrets to use per access token generation request instead of initializing the whole API for each request. -
I am recieving a NoReverseMatch error does anyone know what I'm doing wrong?
Im trying to allow the user to edit an existing entry. But when I include new_entry.html `{% extends "learning_logs/base.html" %} {% block content %} <p> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p> <p>Add a new entry:</p> <form action="{% url 'learning_logs:new_entry' topic.id %}" method='post'> {% csrf_token %} {{form.as_div}} <button name='submit'>Add entry</button> </form> {% endblock content %}` The site throws a NoReverseMatch at /topics/1/ Not too sure where to start looking to solve this issue. Still fairly new to django. Rest of my code bellow views.py def new_entry(request, topic_id): """Add a new entry for a particular topic.""" topic = Topic.objects.get(id=topic_id) if request.method !='POST': #No data submitted; reate a blank form form = Entry() else: #POST data submitted; process data form =EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('learning_logs:topic', topic_id=topic_id) #Display a blank or invalid form context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) urls.py app_name = 'learning_logs' urlpatterns = [ #Home page path('', views.index, name='index'), #Page that shows all topics. path('topics/', views.topics, name='topics'), #Detail page for a single topic path('topics/<int:topic_id>/', views.topic, name='topic'), #Page for adding a new topic path('new_topic/', views.new_topic, name='new_topic'), #Page for adding a new entry path('new_entry/<int:topic_id>/', views.new_entry, name='entry'), ] -
auto-py-to-exe expected str, bytes or os.PathLike object, not NoneType
I'm using auto-py-to-exe to convert my django project in an exe file but I couldn´t: traceback: Running auto-py-to-exe v2.44.1 Building directory: C:\Users\gerar\AppData\Local\Temp\tmp92y6g42v Provided command: pyinstaller --noconfirm --onefile --windowed --add-data 674780 INFO: PyInstaller: 6.9.0, contrib hooks: 2024.7 674795 INFO: Python: 3.12.4 674797 INFO: Platform: Windows-11-10.0.22631-SP0 674813 INFO: Python environment: C:\Users\gerar\AppData\Local\Programs\Python\Python312 674828 INFO: wrote C:\Users\gerar\AppData\Local\Temp\tmp92y6g42v\manage.spec 674837 INFO: Module search paths (PYTHONPATH): ['C:\Users\gerar\AppData\Local\Programs\Python\Python312\Scripts\auto-py-to-exe.exe', File "C:\Users\gerar\AppData\Local\Programs\Python\Python312\Lib\site-packages\PyInstaller\compat.py", line 583, in importlib_load_source mod_loader.exec_module(mod) File "", line 995, in exec_module File "", line 488, in _call_with_frames_removed File "C:\Users\gerar\AppData\Local\Programs\Python\Python312\Lib\site-packages\PyInstaller\hooks\hook-django.py", line 71, in mod_dir = os.path.dirname(hooks.get_module_file_attribute(mod_name)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "", line 277, in dirname File "", line 241, in split TypeError: expected str, bytes or os.PathLike object, not NoneType Project output will not be moved to output folder Complete. -
Attempting to put data from database onto dashboard in Django
So I am following this guide: https://www.youtube.com/watch?v=_sWgionzDoM and am at around 55 mins so far I have the login stuff all working however I am unable to get the dashboard to show my data from the database. The table does show on the admin page with the data however when I go to my dashboard for the user it does not show. Here is the code of my dashboard. {% extends 'page.html' %} {% block content %} {% if messages %} <div class="row mt-3"> {% for message in messages %} {% if message.tags == 'error' %} <div class="col-md-10 col-12 mx-auto alert alert-danger"> {{ message }} </div> {% else %} <div class="col-md-10 col-12 mx-auto alert alert-success"> {{ message }} </div> {% endif %} {% endfor %} </div> {% endif %} <div class="row"> <div class="col-md-10 col-12 mx-auto mt-5"> <div class="d-flex justify-content-end"> <a href="{% url 'main' %}" class="btn btn-primary">+</a> </div> <table class="table table-hover table-striped"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Qty</th> <th scope="col">Category</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> <tbody> {% if items|length == 0 %} <tr> <th scope="row">-</th> <td>no data</td> <td>-</td> <td>-</td> <td>-</td> <td></td> </tr> {% endif %} {% for item in items %} <tr> <th scope="row">{{ item.id }}</th> <td>{{ item.name … -
How To Register Model For Admin Page in Core App?
I defined a model (File) in core app(uploader) and tried to register it for admin page but didnt work. then i tried adding core apps name to installed_apps in setting . after that admin page shows model but when i open it it shows : no such table: uploader_file settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploader' ] views.py : class uploader(View) : def get(self, request) : return render(request, "uploader/pages/upload.html", context={'form': UploadFileForm()}) @method_decorator(csrf_exempt) def post(self, request) : form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): messages.success(request, 'File uploaded successfully!') return redirect('download',link = 'link') messages.error(request, 'Error uploading file.') return render(request, 'uploader/pages/upload.html', {'form': form}) models.py : class File(models.Model) : link = models.CharField(max_length=38) fileField = models.FileField() allowed = models.JSONField() class Meta: app_label = 'uploader' admin.py : from django.contrib import admin from .models import File admin.site.register(File) -
Error while trying to connect Django With ReactNative
I am building a React Native app with Django as the backend. I have set up the login screen in React Native and configured JWT authentication with rest_framework_simplejwt in Django. However, I encounter an error when trying to log in. Within the login screen: const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); const handleSubmission = async () => { try { const response = await axios.post("http://127.0.0.1:8080/api/token/", { username, password, }); if (!response || !response.data) { throw new Error("Invalid server response"); } await AsyncStorage.setItem("accessToken", response.data.access); await AsyncStorage.setItem("refreshToken", response.data.refresh); navigation.navigate("Tab"); } catch (error) { console.error("error", error); const errorMessage = error.response && error.response.data && error.response.data.message ? error.response.data.message : "Whoops! Log In Failed, please try again later 😅."; setError(errorMessage); } }; In Django, views: @api_view(['POST']) @permission_classes([IsAuthenticated]) def create_user(request): serializer = CreateUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'message': "Whoops! error while creating user 🫣", 'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) Serializers: class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] def create(self, validated_data): validated_data['password'] = make_password(validated_data.get('password')) return super(CreateUserSerializer, self).create(validated_data) and I set up cors in settings.py so that I can make API request on my machine: INSTALLED_APPS = [ 'corsheaders', # DEV ONLY ... ] MIDDLEWARE = … -
Heroku DB Connection Limit hit when using Python ThreadPoolExecutor
I have a Django app hosted on Heroku. Some user requests to this app require making long-running queries to external resources. In order to get around the Heroku 30 request timeout, I created a system where these long running queries are given unique IDs and handed to a Python ThreadPoolExecutor so as not to hold off the query. The original query returns immediately and the font end JS code periodically checks in for a results. This system is working great but since deploying that change I routinely get "FATAL: too many connections" errors from my app. It appears as though the automatic connection management Django provides doesn't work when ThreadPoolExecutors are in use. Unfortunately I have to have access to the DB from the spawned thread in order to save the results of the long-running query. Any recommendation as to how I can fix this so DB connections are managed correctly? -
I can't open server in 0.0.0.0 instead it is working in 127.0.0.1 in while using Docker , Django and Postgres
I am a newbie to this. settings.py file is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': 5432, } } Docker file is: FROM python:3 ENV PYTHONUNBUFFERED=1 COPY . /usr/src/app WORKDIR /usr/src/app RUN pip install -r requirements.txt CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] Docker compose file is: version: '3.8' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: password container_name: postgres_db web: tty: true command: python3 manage.py runserver 0.0.0.0:8000 build: . volumes: - .:/usr/src/app ports: - 8000:8000 container_name: django_container environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password POSTGRES_HOST: db depends_on: - db requirements.txt file is: Django psycopg2 docker-compose build docker-compose up docker exec -it django-container bash -l python manage.py migrate docker-compose ps is run and this is the output: ml: versionis obsolete" NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS django_container airline-web "python3 manage.py r…" web 4 minutes ago Up 48 seconds 0.0.0.0:8000->8000/tcp postgres_db postgres "docker-entrypoint.s…" db 3 hours ago Up 48 seconds 5432/tcp above were run server is running in 127.0.0.1:8000 instead of 0.0.0.0:8000. Am I missing something. I am a newbie to this. -
Custom email validation in django form
In my django Account app I have a model for AccountI class Account(AbstractBaseUser): wallet_value = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100) email = models.EmailField(max_length=200, unique=True) phone_number = models.CharField(max_length=20) """SOME OTHER REQUIED FIELD""" date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name", "username"] I also have a Registration form which is responsible for signup feature class RegistrationForm(forms.ModelForm): password = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control", } ) ) confirm_password = forms.CharField( widget=forms.PasswordInput(attrs={"class": "form-control"}) ) first_name = forms.CharField( widget=forms.TextInput( attrs={ "placeholder": "Enter First Name", "class": "form-control", } ) ) last_name = forms.CharField( widget=forms.TextInput( attrs={"placeholder": "Enter Last Name", "class": "form-control"} ) ) email = forms.CharField( widget=forms.EmailInput( attrs={ "placeholder": "Enter Email Adress", "class": "form-control", } ) ) phone_number = forms.CharField( widget=forms.NumberInput( attrs={"placeholder": "Enter Phone Number", "class": "form-control"} ) ) class Meta: model = Account fields = [ "first_name", "last_name", "email", "phone_number", "password", "confirm_password", ] def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(RegistrationForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password dose not match", ) and in my views.py which will handle registeration I … -
I get an error while running django project [closed]
Manage.py file looks like this: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() The terminal executes like this: (venv) PS C:\Users\Administrator\myproject> python manage.py runserver C:\Program Files\Python311\python.exe: can't open file 'C:\\Users\\Administrator\\myproject\\manage.py': [Errno 2] No such file or directory. I followed everystep in the documentation but I constantly receive the error. I am using windows. -
Different session objects in the same session Django
I have a problem with django sessions. This is the first time I've come across this. When accessing request.session in two different views, I get two different SessionStore objects, so I don't get variables from it. I'm writing a variable in one view and I want to get it in another view, that's all I need. All sessions are cleared, cookies are cleared and still the same result. I tried to make a delay of 2 seconds before going to another view in order to have time to write to the db, it does not help. I only use the debug server and the default settings, in middleware the standard settings, I do not use the caches server. I use Django 5.0.7. Has anyone encountered this? enter image description here where do I write the variable class SignYandexView(View): def get(self, request): client = oauth2.Client(client_id=os.getenv("YANDEX_CLIENT_ID")) code_verifier = client.create_code_verifier(length=50) code_challenge = client.create_code_challenge(code_verifier=code_verifier, code_challenge_method="S256") request.session["code_verifier"] = code_verifier print(request.session) return redirect("....") where do I want to get class CallbackYandexView(View): def get(self, request): code = request.GET.get('code') print(request.session) code_verifier = request.session["code_verifier"] -
Django: Error sending email: (530, b'5.7.0 Authentication Required
I am working on a Django project and get the problem with sending email. This is my code in views.py class ForgotPasswordView(APIView): def get(self, request): return render(request, 'login/forgot_password.html') def post(self, request): email = request.data.get('email') if not email: return Response({"message": "", "error": " Email required." }, status=status.HTTP_400_BAD_REQUEST) try: user = User.objects.get(email=email) except User.DoesNotExist: return Response({"message": "", "error": "Email not found." }, status=status.HTTP_400_BAD_REQUEST) #Tao token token = default_token_generator.make_token(user) #Tao link reset_password uid = urlsafe_base64_encode(force_bytes(user.pk)) reset_url = request.build_absolute_uri( reverse('reset_password', kwargs={'uidb64': uid, 'token': token}) ) #Gui email send_mail( 'Reset Password', f'Click following link to reset your password: {reset_url}', os.environ.get('EMAIL_HOST_USER'), [email], #Email nhận fail_silently=False ) return Response({"message": "Mail đặt lại mật khẩu đã được gửi", "error": "" }, status=status.HTTP_200_OK) But the problem is here smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. For more information, go to\n5.7.0 https://support.google.com/mail/?p=WantAuthError d9443c01a7336-1fed7fbf285sm27418485ad.267 - gsmtp', 'sender@gmail.com') I thinh my email setting have some problems so I have a test in tests.py and I work totally fine. from dotenv import load_dotenv load_dotenv() from django.conf import settings from django.core.mail import send_mail import os import sys import django project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(project_root) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "system.settings") django.setup() try: send_mail( 'Test Subject', 'Test message body', os.environ.get('EMAIL_HOST_USER'), ['reciever@outlook.com'], fail_silently=False, ) print("Test email sent successfully") except Exception as e: print(f"Error … -
How to send 401 response with custom login_required decorator after django session expire?
I have a custom login_required decorator which looks like this - def login_required(function): """ Ensure that user is logged in """ def wrap(request, *args, **kwargs): if request.user.is_anonymous: message = { "status": "error", "message": "user login error", "data": "user is not logged in", } return HttpResponse( content=json.dumps(message).encode("utf-8"), status=401, headers=None, content_type="application/json", ) return function(request, *args, **kwargs) return wrap When my request comes in and django session has expired, I see my custom message in the response. However, the status of response code is 302 redirect with the next?=path in url. When I have the network tab open in browser inspect, I sometimes see Cors error but this is not constant. I have configured SESSION_TIMEOUT_REDIRECT, LOGOUT_REDIRECT, LOGIN in settings. Below is what my middleware looks like - MIDDLEWARE = [ "csp.middleware.CSPMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django_session_timeout.middleware.SessionTimeoutMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "core.middleware.admin_pages_middleware.AdminPagesMiddleware", ] I want my response to be 401 and not 302. Could you please let me know what am I missing? Thanks! Tech stack - Python 3.12, Django 5.0 I have tried configuring different django settings. I see the custom error message but not the 401 response. -
KeyError at /verify/ 'order_id'
I have a problem on my store site, when I want to confirm my order, when I click on confirmation on the payment page, it gives this error instead. the error Internal Server Error: /verify/ Traceback (most recent call last): File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\views\generic\base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QK\Desktop\MAworkshop\cart\views.py", line 124, in get order_id = request.session['order_id'] ~~~~~~~~~~~~~~~^^^^^^^^^^^^ File "C:\Users\QK\Desktop\MAworkshop\.venv\Lib\site-packages\django\contrib\sessions\backends\base.py", line 53, in __getitem__ return self._session[key] ~~~~~~~~~~~~~^^^^^ KeyError: 'order_id' [26/Jul/2024 09:38:14] "GET /verify/?Authority=000000000000000000000000000001476833&Status=OK HTTP/1.1" 500 83027 Not Found: /favicon.ico [26/Jul/2024 09:38:14] "GET /favicon.ico HTTP/1.1" 404 5053 I asked some people what should I do to solve my problem and they told me that I didn't set the order_id in the session. view.py from django.shortcuts import render, redirect, get_object_or_404 from account.models import Address from .models import Order, OrderItem, DiscountCode from django.http import JsonResponse from django.http import HttpResponse from product.models import Product from django.conf import settings from django.views import View from .cart_module import Cart import requests import json class CartView(View): def get(self, request): cart = Cart(request) … -
django OAuth Toolkit not getting redirect URI
I am using Django OAuth toolkit and using the following code for OAuth implementation Application = get_application_model() def oauth_login(request): app = Application.objects.get(name="App") #redirect_uri = request.GET.get("redirect_uri", "http://test.com:8000/callback") #redirect_uri = request.GET.get("redirect_uri", "http://test.com:8002/malicious_redirect.html") redirect_uri = request.POST.get("redirect_uri", "http://test.com:8002/malicious_redirect.html") authorization_url = ( f"http://test.com:8000/o/authorize/?client_id={app.client_id}&response_type=code&redirect_uri={redirect_uri}" ) return redirect(authorization_url) def oauth_callback(request): code = request.GET.get("code") if not code: return JsonResponse({'error': 'missing_code', 'details': 'Missing code parameter.'}, status=400) token_url = "http://test.com:8000/o/token/" client_id = Application.objects.get(name="App").client_id client_secret = Application.objects.get(name="App").client_secret #redirect_uri = request.GET.get("redirect_uri", "http://test.com:8002/callback") redirect_uri = request.GET.get("redirect_uri", "http://test.com:8002/unique_redirect.html") data = { "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri, "client_id": client_id, "client_secret": client_secret, } headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': f'Basic {base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()}', } response = requests.post(token_url, data=data, headers=headers) tokens = response.json() print(tokens) if response.status_code != 200: return JsonResponse({'error': 'token_exchange_failed', 'details': tokens}, status=response.status_code) request.session['access_token'] = tokens['access_token'] request.session['refresh_token'] = tokens['refresh_token'] return JsonResponse(tokens) #return redirect('profile') The problem is that if I am logged into the OAuth 2.0 admin panel with superuser credentials, the above code works fine and redirects to the provided URL. Otherwise it doesn't work and uses the LOGIN_REDIRECT_URL = '/profile/' from settings.py. What could be the reason? -
How to Display Total Object Count in Wagtail Snippet ViewSet?
I am currently developing a Wagtail project where I use the ModelAdmin to create custom admin interfaces for my models. When using ModelAdmin, the total object count of a model is displayed below the model name in the list view. However, when I switched to using SnippetViewSet, I lost this functionality.I would like to display the total object count in the list view based on the custom get_queryset method defined in my SnippetViewSet class. ModelAdmin: SnippetViewSet: class PidProviderViewSet(SnippetViewSet): model = PidProvider icon = 'folder' list_display = ["v3", "created"] menu_name = "Unloaded Objects PidProvider" def get_queryset(self, request): qs = PidProvider.objects.filter(foo='foo') return qs register_snippet(PidProviderViewSet) -
Django where to store model-level variables
So I have my model: from django.db import models x_default_coordinate = 0 y_default_coordinate = 0 class Model(models.Model): location1 = gis_models.PointField( srid=4326, default=Point(x_default_coordinate, y_default_coordinate) ) location2 = gis_models.PointField( srid=4326, default=Point(x_default_coordinate, y_default_coordinate) ) Where would be an appropriate place to store the default coordinates? Currently I have them as shown, but that doesn't seem right. -
Sum an aggerated value in Django
I'm trying to achieve the following SQL query in Django: (The table contains the purchases per each day per each location. I want to get the biggest amount of each location, then group them by state to see how much is the max that can be sold in each state) select state, type, sum(amount) from ( select l.state, dd.type, max(amount) as amount from daily_data dd join locations l on l.id = dd.location_id where dd.type in ('purchases', 'returns') group by dd.location_id, dd.type ) group by state, type Where I get this: NY,purchases,80 NY, returns,6 Maine,purchases,125 Maine, returns,12 But I'm geting stuck on how to achieve that in django. I tried this: daily_data.objects.filter(type__in=['purchases', 'returns'] ).values('location', 'type' ).annotate(total=Max('amount') ).values('location__state','type' ).annotate(sum=Sum('total')) But I get an error django.core.exceptions.FieldError: Cannot compute Sum('total'): 'total' is an aggregate I even tried a subquery, but this is generating a bad sql query which yields the query taking forever. subquery = daily_data.objects.filter( location=OuterRef('location'), type=OuterRef('type') ).values('location', 'type').annotate( max_amount=Max('amount') ).values('max_amount') annotated_data = daily_data.objects.filter( type__in=['purchases', 'returns'] ).annotate( max_amount=Subquery(subquery) ).values( 'location__state', 'type' ).annotate( total_max_amount=Sum('max_amount') ).order_by('location__state', 'type') This generates: SELECT "state", "type", SUM(( SELECT MAX(U0."amount") AS "total" FROM "daily_data" U0 INNER JOIN "locations" U1 ON (U0."location_id" = U1."id") WHERE (U1."state" = ("state") AND U2."type" = …