Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't delete Celery Task
I'm having a very weird Issue, I mounted a Django app with Docker, and added a Redis DB to implement Celery tasks, now, yesterday everything was working perfectly, but today I created a new task to test, and now I can't get rid of it, it is on a permanent state of pending, and doesn't matter what I do, I can't stop current_app.AsyncResult(task_status.task_id) from returning it with the pending state. I've tried to remove it celery -A proj purge, current_app.control.purge(), task.revoke(), and current_app.control.revoke(task.id, terminate=True). But despite that it is still returning it. This is how my Redis DB looks like now: There are no tasks ids, Am I doing something wrong, or is there something that I'm misunderstanding? My structure looks something like this: docker-compose.yml version: "3.3" networks: backend: driver: bridge services: django: image: "test:latest" command: python manage.py runserver env_file: - .env volumes: - .:/app ports: - ${PORT_OUT}:8000 networks: - backend links: - db - redis depends_on: - db - redis db: # DB parameters celery: image: "test:latest" command: celery -A djangoproject worker -l debug env_file: - .env volumes: - .:/app networks: - backend links: - db - redis depends_on: - django - redis - db redis: image: "redis:7.0" container_name: … -
AWS App runner - Django - migrations after deploy fails
AS part of the development model changes are made and prepared with makemigrations. When deploying this code to another instance (via Git) the migrations need to be run on the database of the instance. I have configured the apprunner.yaml file as: ['''version: 1.0 runtime: python3 build: commands: build: - pip install -r requirements/production.txt post-build: - source /var/app/venv/*/bin/activate - python manage.py migrate - deactivate run: runtime-version: 3.8.16 command: sh startup.sh network: port: 8000'''] I've also tried it without the 'post-build' section. startup.sh contains: '''#!/bin/bash gunicorn config.wsgi:application''' also tried a version of the startup.sh with below - also fails '''#!/bin/bash python manage.py migrate && gunicorn config.wsgi:application''' Log: 12-01-2023 10:05:40 AM [AppRunner] Reading apprunner.yaml config file. 12-01-2023 10:05:40 AM [AppRunner] Successfully Validate configuration file. 12-01-2023 10:05:42 AM [AppRunner] Starting source code build. 12-01-2023 10:09:00 AM [AppRunner] Service update failed. For details, see service logs. I've tried variants of the yaml file as mentioned, one without the post-build, a post-build with on,y the Python... line, variants of the startup.sh file as above. I've also tried using just the build settings it falls back on to change the start command from gunicorn config.wsgi:application to Python manage.py migrate && gunicorn config.wsgi:application. All just fails and rolls … -
Django 4.0.10 Migration Error: 'ManyToManyField' object has no attribute 'm2m_reverse_field_name'
I am experiencing a migration issue in Django 4.0.10 using Python 3.12.0 and PostgreSQL as my database. The error occurs during the migration process and seems to be related to ManyToManyField attributes in my CustomUser model. Error message: AttributeError: 'ManyToManyField' object has no attribute 'm2m_reverse_field_name' This issue arises when I run python manage.py migrate. It seems to be triggered by a specific migration file that modifies ManyToManyField relationships. Here are the relevant parts of my CustomUser model from models.py and the problematic part of the migration file: models.py (CustomUser model excerpt): class CustomUser(AbstractUser): # Basic personal information height = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True, help_text="Height in centimeters") weight = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True, help_text="Weight in kilograms") # Health and dietary information activity_level = models.CharField(max_length=50, choices=[('sedentary', 'Sedentary'), ('light', 'Light Activity'), ('moderate', 'Moderate Activity'), ('active', 'Active'), ('very_active', 'Very Active')], default='sedentary', help_text="Activity level of the user") health_goal = models.CharField(max_length=100, choices=[('lose_fat', 'Lose Fat'), ('gain_muscle', 'Gain Muscle'), ('maintain_weight', 'Maintain Weight'), ('improve_fitness', 'Improve Fitness')], default='maintain_weight', help_text="Primary health goal") dietary_restrictions = models.ManyToManyField('DietaryRestriction', blank=True) food_preferences = models.ManyToManyField('FoodItem', blank=True) # Nutritional needs daily_caloric_intake = models.IntegerField(null=True, blank=True, help_text="Recommended daily caloric intake") daily_protein_needs = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True, help_text="Recommended daily protein intake in grams") daily_carb_needs = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True, help_text="Recommended daily … -
Get access to the last object from foreign key
My models are here: class UserToPackageMeta(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="package_metas" ) package = models.ForeignKey( "platforms.Package", on_delete=models.RESTRICT, related_name="user_metas" ) class Package(models.Model): platform = models.ForeignKey( Platform, on_delete=models.CASCADE, related_name="packages" ) class Platform(models.Model): slug = models.CharField(max_length=125, blank=True, null=True) I want to write a query to get users based on platfrom slug on last package they have because any user can have diffrante packages: I tried this: users = users.filter(package_metas__package__platform=platform) But this won't consider only the last package for each user. -
why is my signup and login not created and authenticated when I put it in the same function in my django project?
initally I seperate the registration and loginUser function on my views.py, which work just fine creating the user. user created on DB and logout also works fine. but I had problems with the login that it won't log the user in withou giving any error alert. I figured that me putting the login and signup form in the same html file might be the problem so I tried to merge the register and loginUser function def registerUser(request): form = CreateUserForm() if request.method=="POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + form.cleaned_data.get('username')) email = form.cleaned_data.get('email') Customer.objects.create(username=User.objects.get(username=user), email=email) return redirect('register') context={'form':form} return render(request, 'store/register.html',context) def loginUser(request): if request.method =="POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return redirect('store') else: messages.info(request, 'Incorrect username or password') context={} return render(request, 'store/login.html',context) here are the merged function views.py from django.shortcuts import render, redirect from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect import json import datetime from .models import * from . utils import cookieCart, cartData, guestOrder # for userCreation from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .forms import CreateUserForm, LoginForm from django.contrib import messages # authenticate user from django.contrib.auth import authenticate, … -
running django makemigrations twice generates two migrations, one to add a field and one to alter that same field … to itself
One would expect that running makemigrations twice in a row would be a no-op for the second one, but in fact I get two migrations, and the second one can't be applied (an exception is thrown trying to access None.startswith). Output somewhat sanitized: % ./manage.py makemigrations Migrations for 'foo': foo/migrations/0004_foo.py - Add field foo to bar % ./manage.py makemigrations Migrations for 'foo': fooo/migrations/0005_alter_foo.py - Alter field foo on bar The contents of the migrations are basically: operations = [ migrations.AddField( model_name="bar", name="foo", field=models.ForeignObject( default=1, from_fields=["original_id", "original_date"], on_delete=django.db.models.deletion.PROTECT, related_name="+", to="foo.baz", to_fields=["id", "date"], ), preserve_default=False, ), for the first, and then the "alteration": operations = [ migrations.AlterField( model_name="bar", name="foo", field=models.ForeignObject( from_fields=("original_id", "original_date"), on_delete=django.db.models.deletion.PROTECT, related_name="+", to="payment.payment", to_fields=("id" "date"), ), ), ] Attempting to run the migration results in: File "/Users/wolfson/.local/share/virtualenvs/message_digest-gQFszokA/lib/python3.11/site-packages/django/db/backends/postgresql/operations.py", line 189, in quote_name if name.startswith('"') and name.endswith('"'): ^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'startswith' -
Error 500 rom Djanjo when trying to send my form data in JavaScript to my Django Url
I am trying to build a ToDo List in Djanjo and I am having issues while trying to build the edit view functionality, below is my home.html file <div class="col-md-7 col-lg-7" style="height: 450px; overflow: scroll;"> <!-- List of all the tasks for the day --> {% for task in tasks %} <div class="card m-1"> <div class="card-body"> <span id="task_{{ task.pk }}_text">{{ task.task }}</span> <span style="position: relative; float: right;"> <a href="{% url 'mark_as_done' task.pk %}"class="btn btn-success"><i class="fa fa-check"></i> Mark as Done</a> <a href="{% url 'delete_task' task.pk %}" class="btn btn-danger"><i class="fa fa-trash"></i></a> <!-- When this button is clicked, a textbox/form will appear, after it appears and you press submit task is updated --> <a onclick="showTextBox('{{ task.pk }}')" class="btn btn-primary"><i class="fa fa-pencil"></i></a> <form id="textbox_{{ task.pk }}" onsubmit="saveValue(event, '{{ task.pk }}')" method="post"> {% csrf_token %} <input type="text" id="inputValue_{{ task.pk }}" name="edited_task" placeholder="Update task"> <input type="submit" value="Submit"> </form> </span> </div> </div> {% endfor %} </div>`` Next is my script, where I try to send the data to the backend <script> function showTextBox(key){ /*console.log(100); console.log(`textbox_${key}`);*/ var textbox = document.getElementById(`textbox_${key}`); textbox.classList.toggle('hidden-textbox'); } function saveValue(event,key){ /*each task object has a primary key associated to it*/ event.preventDefault(); var primary_key=key; var enteredValue = document.getElementById(`inputValue_${primary_key}`).value; const base="{% url 'edit' 123 %}".slice(0, -4); … -
Problems with pyenv virtualenv and Django 1.6
I installed python 2.7 using pyenv to run an older project that still uses Django 1.6, but I can't get the path to work. Even thou I have the virtualenv that I created with 2.7 activated, and all pip requirements installed, whenever I try to run the project I get the following error: ImportError: Could not import settings '***.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named objects *Name of the project was replaced by *** When I try and print the os path I get this result: \<module 'posixpath' from '/Users/userx/.pyenv/versions/2.7.18/lib/python2.7/posixpath.pyc'\> Instead of getting the directory for the Django project. Does anyone know how can I get a python version installed with pyenv to run on the correct directory? ps.: already tried this ImportError: Could not import settings and already tried this Issues with pyenv-virtualenv: Python and PIP not changed when activating / deactivating virtual environment and everything regarding pyenv init settings and path -
Server Error (500) on django app production
I am trying to deploy a Django Application on Render. In my project, I have some number of apps that have their own urls file. Then, in the project's url, I included them. Have a look at the project's url: urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('about/', include('about.urls')), path('services/', include('services.urls')), path('teams/', include('team.urls')), path('contact/', include('contact.urls')), path('kbdash/', include('management.urls')), path('auth/', include('users.urls')), ] And for every app the url looks like this: urlpatterns = [ path('', about_page, name='about'), ] all these urls work except for the path('kbdash/', include('management.urls')) kbdash/ is for managing all url in management app. Below is the url of management app: urlpatterns = [ path('', views.Dashboard.as_view(), name='dashboard'), path('fuels/', views.fuel_list_view, name='fuel_list'), path('fuels/manage/', views.manage_fuel_view, name='manage_fuel'), path('fuels/manage/<int:pk>/', views.manage_fuel_view, name='manage_fuel_edit'), path('fuels/add/', views.save_fuel_view, name='save_fuel'), path('fuels/detail/<int:pk>/', views.fuel_detail_view, name='fuel_detail'), path('fuels/delete/<int:pk>/', views.fuel_delete_view, name='delete_fuel'), path('stocks/', views.stock_list_view, name='stock_list'), path('stocks/manage/', views.manage_stock_view, name='manage_stock'), path('stocks/manage/<int:pk>/', views.manage_stock_view, name='manage_stock_edit'), path('stocks/add/', views.save_stock_view, name='save_stock'), path('stocks/detail/<int:pk>/', views.stock_detail_view, name='stock_detail'), path('stocks/delete/<int:pk>/', views.stock_delete_view, name='delete_stock'), path('inventory/', views.inventory_view, name='inventory'), path('sales/', views.sales_list_view, name='sales'), path('sales/manage/', views.sales_manage_view, name='manage_sale'), path('sales/manage/<int:pk>/', views.sales_manage_view, name='manage_sale_edit'), path('sales/add/', views.sales_save_view, name='save_sale'), path('sales/detail/<int:pk>/', views.sales_detail_view, name='sale_detail'), path('sales/delete/<int:pk>/', views.sales_delete_view, name='delete_sale'), path('sales/report/', views.sales_report_view, name='sales_report_page'), path('sales/report/<str:report_date>/', views.sales_report_view, name='sales_report') ] all the urls in main urls file are working except for the kbdash/ Visiting kbdash/ and any link under kbdash/ throw Server Error (500) I have no idea why … -
Forbidden (CSRF cookie not set.): api/endpoint/ 403
I'm trying to implement getting information from a form. My stack: Vue and DRF. The problem is that I implemented receiving information from the form to the server, but without a CSRF token. Then I wanted to include the decorator in APIView. ` @method_decorator(csrf_protect, name='dispatch') class LiteContactView(APIView): permission_classes = [permissions.AllowAny] def post(self, request): serializer = LiteContactSerializer(data=request.data) if serializer.is_valid(): print(serializer.validated_data['phone_number'], serializer.validated_data['full_name']) message = _('Message was sent succesfully') return Response({'message': message}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ` On vue file i am using axios ` if(!this.error.lenght) { axios .post(`${this.$i18n.locale}/submit-contact/`, this.form) .then(response => { this.form.full_name = '' this.form.phone_number = '' this.message = response.data.message; this.$emit('submitLightForm', response.data) }) .catch(error => { console.log(error) }) } ` My settings.py file: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', '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', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:5173', ] CSRF_TRUSTED_ORIGINS = ['http://localhost:5173'] I tried different options to get a token with a cookie but I couldn’t get it! That's my error Forbidden (CSRF cookie not set.): -
I am trying to transfer data to the server in the database from the front (react)
I'm just learning react and I can't transfer some data to the server in any way, they come with a null value. Here's an example, I select a category from the list, but an empty value (null) comes, that's what json shows in the browser console. The same is true in the database in the column "case_category_id" the value is null Example of output in the browser, after saving the card { "original_name": "7", "author": null, "case_category": null, "article": 100, "pub_date": "2023-11-30T10:24:08.346215Z", "preliminary_hearing": "2023-01-01" } The code itself import React, { useState, useEffect } from 'react'; import axios from 'axios'; import MyInput from './UI/input/MyInput'; import MyButton from './UI/button/MyButton'; const AddBusinessCard = ({ create }) => { const [formData, setFormData] = useState({ original_name: '', author: '', case_category: '', article: '', pub_date: '', preliminary_hearing: '', }); const [categoryList, setCategoryList] = useState([]); useEffect(() => { axios .get('http://localhost:8000/business_card/category/') .then(response => { setCategoryList(response.data); }) .catch(error => { console.error('Error fetching category list:', error); }); }, []); const handleChange = event => { const { name, value } = event.target; setFormData(prevState => ({ ...prevState, [name]: value, })); }; const handleSubmit = event => { event.preventDefault(); if (!formData.case_category) { console.error('Please select a category.'); return; } const formattedData = … -
Optimizing python function
Somebody can tell me why this takes 3 seconds, is to show a list of new products i already have all the fks in prefetch/select related @cached_property def products(self): return Product.catalogo.base() def new_products(self): """ queryset de productos nuevos de la categoría base """ products = self.productos random_qty = 16 products_ids = [x.id for x in products] last_product_id = products_ids[-1] qty = last_product_id - settings.CANT_PRODUCTOS_PARA_NOVEDADES ids = [x.id for x in products if x.id >= qty and x.stockrecords.all() and x.images.all()] if ids and len(ids) >= random_qty: ids = random.sample(ids, random_qty) return [x for x in products if x.id in ids] how can i optimize this -
Django form now showing input fields
I've tried to fix this issue with chat GPT for a while now, but it says that everything okay, but it clearly ain't. For now I;m trying to just run the e-mail field before doing the rest. Here are my files: forms.py: from django import forms class SignupForm(forms.Form): email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput()) firstname = forms.CharField(widget=forms.TextInput()) lastname = forms.CharField(widget=forms.TextInput()) isOwner = forms.BooleanField() the form: <form method="post" action="{% url 'signup' %}" class="registerForm"> {% csrf_token %} {{ form.as_p }} <div class="header">Registration</div> <div class="loginText">E-mail:</div> <div class="loginInformation"> {{ form.email.label_tag }} {{ form.email }} </div> </form> and my controller: @api_view(('POST',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def signup(request): if request.method == "POST": form = SignupForm(request.POST) if form.is_valid(): account = accountService.signup( request.POST["email"], request.POST["password"], request.POST["firstName"], request.POST["lastName"], request.POST["isOwner"] ) if account: return Response({'account': account}, template_name="index.html") return render(request, "signup.html") -
Input field using tailwind 2.2.16 in django form
I am using tailwind 2.2.16 in my Django project. I want to style the form, but the input fields are misbehaving and a weird looking border is encircling them. Please help me create a decent looking input field. <form method="post" class="bg-green-200 shadow-lg m-10 rounded p-10 w-2/5"> {% csrf_token %} <div class="mb-4"> <label class="text-gray-700 text-xl font-bold" for="username">Username</label> <div class="shadow appearance-none border rounded py-2 px-3 mr-10">{{form.username}}</div> </div> <div class="mb-4"> <label class="text-gray-700 text-xl font-bold" for="username">Password</label> <div class="shadow appearance-none border rounded py-2 px-3 mr-10">{{form.password}}</div> </div> <button type="submit">Login</button> </form> ]1 -
UpdateView can't update (Django, HTMX)
I'm working on a Django app similar to some streaming platforms, as I am building a portfolio. In the database management part (where I add, edit or delete films), I'm trying to use UpdateView (as I did on other projects) to update the films informations. The link works, I go to the edit page where the form is populated with the already existing informations, but when I save after an edit, I got my message 'This film is already in the database', a message I created that should only appears when I add a film (with a modal and an API call). It's not even in the same view... I've tried everything I could, searched for hours online to find a solution, but I'm still stuck. What I am trying to understand is what happens when I click on the save button. It looks like it redirects to the ManageFilmsView where it tries to create a new entrance to the database. Which is weird, as it is called UpdateView... Should I overwrite something in the UpdateView ? So, if somebody had the same problem, or can help me find a solution, it would be great ! (My code is probably … -
Designing a DRF-React App with Configurable Social and LDAP Authentication
I'm working on a DRF + React and aiming to implement various authentication methods, including social authentication (Google, Facebook, GitHub) and LDAP server integration. I want the flexibility to configure these authentication methods according to my requirements. Specifically, I would like to remove or add social authentication providers as needed. The key requirements are: Social authentication (Google, Facebook, GitHub). LDAP server authentication. Configurability to easily add/remove authentication providers. JWT-based session login authentication. I want to ensure that the solution is maintainable, scalable, and provides the desired flexibility in configuring authentication methods. Any examples or references to existing projects with similar setups would be greatly appreciated. This is what I am currently doing, I have configured a google auth which has a client based flow - Users click on sign in with google from frontend - Google returns a one time code - Then frontend send this code to backend and backend validates this with google and returns user details in form of jwt token - jwt token is stored on local storage, and this token is used to call each and every API as an authorisation header, if token is expired/invalid backend sends 403 forbidden and user is logged out. … -
How can I tell django how to revert custom migration?
I have two simple migrations: 0001_initial.py # Generated by Django 4.2.7 on 2023-11-30 11:15 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.RunSQL( """ CREATE TABLE comments ( id SERIAL PRIMARY KEY, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, contents VARCHAR(240) NOT NULL ); """ ), ] 0002.py # Generated by Django 4.2.7 on 2023-11-30 11:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("polls", "0001_initial") ] operations = [ migrations.RunSQL( """ ALTER TABLE comments RENAME COLUMN contents to text; """ ), ] I run python manage.py migrate Then I want to undo the 0002 migration I run python manage.py migrate polls 0001 But Django does not know how to undo the changes from the second migration. How can I tell Django that for undoing the changes from the 0002 migration I need to run this SQL: ALTER TABLE comments RENAME COLUMN text to contents; I tried searching but without success. -
unsupported locale setting en DigitalOcean, Django y Python
tengo este error en producción en DigitalOcean, con un droplet Ubuntu 20.04, el proyecto es en Python con Django como framework. error Esta es mi función de home. home He estado intentado cambiar la variable LC_ALL en C, pero no soluciona el error. Estos es lo que me aparece al hacer el locale -a comando. locale -a comando -
Replacement for Fabric's Execute Function in Python 3.10
I'm in the process of updating a Python project that extensively uses the fabric.api module for remote command execution. The existing code relies heavily on the execute function, which has been removed from the newer versions of Fabric. My current Fabric version is 3.2.2. The execute function is used when working with different instances of the project. Here’s an example of how the execute function is currently used: if tmp_url == "innomanager": execute(delete_instance, "development", True, name) else: execute(delete_instance, "production", True, name) I’ve looked at the Fabric documentation for upgrading from older versions. According to the documentation, the execute function has not been rewritten yet for new versions of Fabric. Based on the documentation, it’s not clear how to achieve similar functionality without the execute function. How could I perform similar actions without the use of execute? -
How to get Django Organization Specific Microsoft Authentication working?
I know this is a broad question. I am currently trying to figure out how to get Django app to only accept organization specific Microsoft accounts. I do not need a step by step answer but some guidance on what I should go research or do. -
django-database-view get_str() depends on older source code version during django migrations
I am facing a problem in a project. There is django-database-view from https://github.com/manuelnaranjo/django-database-view used to inject SQL-Commands during the migrations into the database to create views. This worked in the past so far and the problem I have, did not show up for existing installations, where the original migration step had been already executed. Now, there was a change in the SQL-string of the DbView which is returned by get_view_str() and the original migration step fails, because CreateView calls internally get_view_str() and receives the string of the current version of the code base. However, this new string depends on db-tables which had been created after the original migration step, that´s why this step fails now. There is also a later migration step to apply the changes of the view, but that point is not reached anyway. As it is not possible for me to change the original migration step anymore because it is too far in the past and we can not roll back, I have to modify somehow the get_view_str() method of the DbView to return the proper one for the according migration step. This is a part of the original migration script: operations = [ CreateView( name='DbViewModelExample', fields=[ … -
DRF dynamic select field
class DealSerializer(serializers.ModelSerializer): organization = serializers.PrimaryKeyRelatedField(style={'placeholder': 'Организация'}, label='Организация', required=True, queryset=Organization.objects.all()) services = serializers.PrimaryKeyRelatedField( queryset=Service.objects.all(), many=True, label="Услуги", required=True) How to make sure that the services, or rather their queryset, change in the template depending on the choice of the organization? P.S. Each organization has its own services. It must work without reload page. -
SyntaxError: future feature annotations is not defined using python 3.9
I am using python 3.9 in a virtual environment. The only solution I can find just says to use python 3.7 or higher and try using a virtual environment to ensure it is. I am doing both and as you can see from the backtrace, it is indeed using 3.9. Internal Server Error: /api/auth/token-auth/ Traceback (most recent call last): File "/workspace/mktplace/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/workspace/mktplace/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 165, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/workspace/mktplace/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 288, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/workspace/mktplace/env/lib/python3.9/site-packages/django/urls/resolvers.py", line 545, in resolve for pattern in self.url_patterns: File "/workspace/mktplace/env/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/workspace/mktplace/env/lib/python3.9/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/workspace/mktplace/env/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/workspace/mktplace/env/lib/python3.9/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/workspace/mktplace/market/market/market/urls.py", line 47, in <module> path(prepath, include('reporting.urls'), name='payg_v1_reporting') … -
How to change the button name after performing the corresponding action?
In this code, the action is performed completely, but after adding the product to the list:: 1- The button doesn't change its name from Add to Remove. 2- The product information that's in watchlist.html is not displayed, that is, the output's: Products: Category: First Bid: $ views.py: @login_required(login_url="login") def watchlist(request, username): products = Watchlist.objects.filter(user = username) return render(request, 'auctions/watchlist.html', {'products': products}) @login_required(login_url="login") def add(request, productid): product_id = request.GET.get('productid', False) watch = Watchlist.objects.filter(user = request.user.username) for items in watch: if (items.watch_list.all) == int(productid): return watchlist(request, request.user.username) else: return remove(request, productid) new_watch = Watchlist(product_id, user=request.user.username) new_watch.save() messages.success(request, "The product has been added to your WatchList.") return product_detail(request, productid) @login_required(login_url="login") def remove(request, pid): list_ = get_object_or_404(Watchlist, pk = pid) messages.success(request, "The product was removed from your WatchList.") list_.delete() return redirect("index") product_detail.html: {% if product in watch %} <form method= "get" action = "{% url 'remove' product.id %}"> {% csrf_token %} <button type = "submit" value = "{{ product.id }}" name = "productid" >Remove from Watchlist</button> </form> {% else %} <form method= "get" action = "{% url 'add' product.id %}"> {% csrf_token %} <button type = "submit" value = "{{ product.id }}" name = "productid" >Add to Watchlist</button> </form> {% endif %} watchlist.html: {% … -
PostgreSQL - Custom ordering for each user's income for each item's price
I have two tables in Django Item column_name | data_type -------------+----------- id | integer price | integer User column_name | data_type -------------+----------- id | integer amount | integer Item's price rarely changes while user's amount might change once a day or more frequently. Ordering in Django need be done be like below. Show items whose price is less than or equal current user's amount (affordable) - order by item price high to low Then rest of the items (unaffordable) - order by item price high to low I need to show items in this order with pagination. We have around 200k items and around 100k users. Around 100 items are added per day. All these need to be updated whenever an item/user changes/added/removed. Django model from django.db import models class Item(models.Model): id = models.AutoField() price = models.IntegerField() class User(models.Model): id = models.AutoField() amount = models.IntegerField() I thought of creating an extra column but that will has to change for each call for all items. Has anyone built something like this? Should I use some other DB tool? I am open to suggestions. Thanks