Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when trying to install Django using pip on Windows [duplicate]
I am new to Python and trying to install Django framework on my Windows machine using pip. However, I'm encountering the following error: pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + pip install django + ~~~ + CategoryInfo : ObjectNotFound: (pip:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I'm not sure what this error means and how to resolve it. Can someone please guide me on how to fix this issue? Keep in mind that I'm a beginner and may need detailed instructions. Thank you in advance for your help! #python, #django, #pip, #windows, #installation, #beginner Its a screen-shot of erorr -
How do I load a django template using absolute paths?
I have a template xyz.html stored in the path /doc-templates/ so the full path is /doc-templates/xyz.html I'm trying to load the template using my_template = get_template('/doc-templates/xyz.html') But this raises the TemplateDoesNotExist exception. Any ideas before I roll out my own template loader? PS: Yes I know where Django templates should be, I just want to see if this is possible now that everything is being "dockerized" I have explicitly enabled django.template.loaders.filesystem.Loader and set the DIRS to a non empty list as documented but it seems to be ignoring the absolute path (possibly appending it to the DIRS list) -
django admin foreignkey icons not active
In the django admin (4.2) I can find in case of foreignkey fields the icons for editing, adding, deleting and viewing the relevant foreignkey element. However, only the add button is active in my case. How can I activate the other icons= -
Issue with Google login using Django allauth: Not prompted to select Google account in Incognito mode or certain browsers (opera, Edge)
I'm using Django allauth for Google login in my web application. Everything works fine, but I've encountered an issue where when users try to log in using Google in Incognito mode or with certain browsers like Opera or Edge, they are not prompted to select a Google account. Instead, it automatically logs in with the previously logged-in Google account. Here's a snippet of my settings in settings.py: SITE_ID = 1 SOCIALACCOUNT_ADAPTER = 'microdistribution.users.adapters.CustomSocialAccountAdapter' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' SOCIALACCOUNT_LOGIN_ON_GET=True ACCOUNT_LOGOUT_ON_GET = True SOCIALACCOUNT_EMAIL_AUTHENTICATION = True ACCOUNT_SESSION_REMEMBER = False SOCIALACCOUNT_PROVIDERS = { 'google': { 'AUTH_PARAMS': {'access_type': 'online'}, } } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'allauth.account.middleware.AccountMiddleware', #new 'microdistribution.utils.middleware.DynamicSiteMiddleware', #new ] INSTALLED_APPS = [ 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] Custom Adapter im using class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form=None): user = sociallogin.user # Check if the user already exists existing_user = self.get_existing_user(user) if existing_user: return existing_user # If the user doesn't exist, create a new one try: new_user = super().save_user(request, sociallogin, form) new_user.name = sociallogin.account.extra_data.get('name') new_user.client_uid_id = User.objects.get(id = settings.CLIENT[request.META['HTTP_HOST']].client_uid_id) new_user.save() return new_user except Exception as e: print(f"Error While Creating User: {e}") return None def get_existing_user(self, user): existing_user = None try: … -
React & Django - WARNING:django.request:Forbidden: /api/user - SessionAuthentication
I'ved created this Django & React project (https://github.com/axilaris/docker-django-react-celery-redis), and I'm having difficulties with accessing API with SessionAuthentication. You can easily spin off with: docker-compose build docker-compose up I keep getting access issue with accessing /api/user (you can test with register, login) backend_container | Forbidden: /api/user backend_container | WARNING:django.request:Forbidden: /api/user You can look more the logs here: https://gist.github.com/axilaris/7b7a5c50f4f7112b440eaf8ef8100d9d In my django api code (backend/user_api/views.py): class UserView(APIView): permission_classes = (permissions.IsAuthenticated,) authentication_classes = (SessionAuthentication,) def get(self, request): serializer = UserSerializer(request.user) return Response({'user': serializer.data}, status=status.HTTP_200_OK) In settings.py: CORS_ALLOWED_ORIGINS = [ 'http://localhost', 'http://127.0.0.1', 'http://0.0.0.0', ] CORS_ALLOW_CREDENTIALS = True INSTALLED_APPS = [ .. 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] and in react: axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.withCredentials = true; useEffect(() => { client.get("/api/user") .then(function(res) { setCurrentUser(true); }) .catch(function(error) { setCurrentUser(false); }); }, []); why whenever after I login and I reload back localhost on the browser it has forbidden /api/user and goes back to the login page. I feel the CORS are setup correctly and credentials are set true on both backend and frontend. -
Django Model Choice Form display logo + name
How to make a form populated from a database values to display the image from the URLField (team.logo) and the name (team.name) next to it. I am trying to achieve this through the following code but it ignores the image display part and only shows the team name: class TeamModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, team): return format_html(f'<img src="{team.logo}" class="form-logo">{team.name}') class TeamChoiceForm(forms.Form): teams_extra = Team.objects.all() team_home = TeamModelChoiceField( queryset=teams_extra, empty_label="Team Home" ) team_away = TeamModelChoiceField( queryset=teams_extra, empty_label="Team Away" ) -
Bad Request: /dj-rest-auth/google/ . Request Failed with status code 400
With dj-rest-auth, google login, I keep getting Request failed with status code 400 and cant figure out what's wrong. All the other API end points are working, except for social login. The page redirects to Google Signup Page, and then the URL also contains the "key", but doesnt seem to login for some reason. Kindly help. //Action.js export const googleLogin = ( code ) => async dispatch => { if ( !localStorage.getItem('access') ) { const config = { headers: { "Content-Type": "application/json" } }; const body = JSON.stringify({ code }) try { const res = await axios.post("http://localhost:8000/dj-rest-auth/google/", body, config) dispatch ({ type: TYPE.LOGIN_SUCCESS, payload: res.data }) } catch (err) { dispatch ({ type: TYPE.LOGIN_FAIL, error: err.message }) } } else { dispatch( verify() ); dispatch( getUser() ); } } //reducer.js const AuthReducer = (state=initialState, action) => { const { type, payload } = action; switch (type) { case TYPE.LOGIN_SUCCESS: localStorage.setItem('access', payload.access); return { ...state, access: payload.access, isAuthenticated: true, user: payload.user, message: "Login has successed" } case TYPE.LOGIN_FAIL: localStorage.removeItem('access'); return { ...state, access: null, isAuthenticated: false, user: null, message: "Login has failed" } default: return state; } } //Header.js const Layout = (props) => { let location = useLocation(); useEffect (() … -
n.data.map is not a function in React
I am getting this error which may indicate the map function require arrays, while the data provided is not of the data type required. The console output in the browser Uncaught (in promise) TypeError: n.data.map is not a function t watchlistStore.jsx:14 d watchlistStore.jsx:2 O watchlistStore.jsx:2 E watchlistStore.jsx:2 em watchlistStore.jsx:2 a watchlistStore.jsx:2 promise callback*em watchlistStore.jsx:2 a watchlistStore.jsx:2 n watchlistStore.jsx:2 n watchlistStore.jsx:2 fetchStocks watchlistStore.jsx:22 im indexWatchlist.jsx:15 React 3 k scheduler.production.min.js:13 T scheduler.production.min.js:14 53 scheduler.production.min.js:14 Webpack 12 import React from "react"; import { create } from 'zustand'; import axios from 'axios'; const watchlistStore = create((set) => ({ stocks: [], filteredStocks: [], fetchStocks: async () => { console.log(`Fetching Watchlist`); const response = await axios.get('/watchlist'); if (response.data != 0) { const stocks = response.data.map((stock) => { return { symbol: stock.symbol, name: stock.name, } }); set({ stocks }); }; }, })); export default watchlistStore; The data to be fetched /watchlist {'symbol': 'WISH', 'name': 'ContextLogic Inc.'}{'symbol': 'GTII', 'name': 'Global Tech Industries Group, Inc.'}{'symbol': 'CCFN', 'name': 'CCFNB Bancorp, Inc.'}{'symbol': 'GAME', 'name': 'Engine Gaming and Media, Inc.'}{'symbol': 'SEMR', 'name': 'Semrush Holdings, Inc.'} The view in the backend: def watchlist(request): if request.user.is_authenticated: dataList = list() for x in Tickers.objects.filter(users=request.user): dataList.append({'symbol':x.symbol, 'name':x.name}) return HttpResponse(dataList) else: return HttpResponse('Watchlist is empty') -
Sessionid is not set to 'application/Cookies' in developer tools
I'm trying to implement a login function with Django and React. Reference: https://www.youtube.com/watch?v=diB38AvVkHw&ab_channel=Djangoroad When a post method is sent to login, the sessionid is set only in 'network/cookies'. Checking the 'application/cookies', only csrfToken is set. I'm not sure why the sessionid wasn't set to the Cookies. Is there anything to cause this problem? here is UserLogin view in django views.py class UserLogin(APIView): permission_classes = (permissions.AllowAny, ) authentication_classes = (SessionAuthentication, ) def post(self, request): data = request.data assert validate_email(data) assert validate_password(data) serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): user = serializer.check_user(data) login(request, user) return Response({'user_id': user.user_id}, status=status.HTTP_200_OK) Here is the react function to submit login form. function submitLogin(e) { e.preventDefault(); client .post("/api/login", { email: email, password: password, }) .then(function (res) { setCurrentUser(true); setUserId(res.data.user_id); }); } -
No module of _ffi found when create superuser
Python manage.py createsuperuser in django project in virtuelenv, reporting error: No module of _ffi found. Error Image 1 Error image 2 I got some clue from google. for example update cffi and argon2, run python from different locations. But nothing works. Thanks in advance! -
How to sort object by number of orders that is obtained by `get_queryset` field
Here in code below I can get all the number of orders that are assigned to business. But here is the question, how can I edit this code so that I can sort users by which business that has most orders? class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='ordersauthor') profile = models.ForeignKey(User, on_delete=models.CASCADE,related_name='orderscheck') article = models.ForeignKey(Article, null=True, blank=True, on_delete=models.CASCADE,related_name='ordersarticle') timestamp = models.DateTimeField(auto_now_add=True) --------- class PublicUserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = User.objects.all().order_by('#HIGHEST NUMBER OF ORDERS') serializer_class = UserSerializer filter_backends = [filters.SearchFilter,DjangoFilterBackend] pagination_class = StandardResultsSetPagination def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .annotate( num_orders=Count( 'orderscheck', orders__timestamp__range=Q( orderscheck__timestamp__range=(date.today(), date.today() + timedelta(days=7)) ), ) ) ) ---------- class UserSerializer(serializers.ModelSerializer): orders = serializers.IntegerField(read_only=True, source='num_orders') -
hugchat is not remembering my name, integrated with django
def ChatBotCreateCookie(husername=husername, hsecret=hsecret): sign = Login(husername, hsecret) cookies = sign.login() cookie_path_dir = "./" sign.saveCookiesToDir(cookie_path_dir) return cookies def ChatBotVerifyCookie(husername=husername): if os.path.exists(f"{husername}.json"): cookie = f"{husername}.json" else: ChatBotCreateCookie() cookie = f"{husername}.json" return cookie def ChatBotLogin(): cookie = ChatBotVerifyCookie() chatbot = hugchat.ChatBot(cookie_path=cookie) return chatbot def LandingFunction(request): return render(request, 'index.html') def ChattingRequest(request): ChatRequestString = request.GET['ReqText'] ChatConn = ChatBotLogin() ChatResponse = ChatConn.chat(ChatRequestString) print("Request="+ChatRequestString+"\nResponse="+str(ChatResponse)) return HttpResponse(str(ChatResponse)) This is my view, i have logged in using cookie but maybe hugchat is not creating a session for my requests.(I have done it with core python using while and it worked fine, how can i do the same here) -
Django session - recently viewed not showing in html
im working on a project using django framework. Im having issues in showing on the html the recently viewed items where the user (logged in) clicked before. This is my index.html that shows the recently_viewed items <div class="mt-6 px-6 py-12 bg-gray-100 rounded-xl"> <h2 class="mb-12 text-2xl text-center">Recently Viewed Items</h2> <div class="grid grid-cols-3 gap-3"> {% if recently_viewed_qs %} {% for item in recently_viewed_qs %} <div> <a href="{% url 'item:detail' item.id %}"> <div> <img src="{{ item.image.url }}" class="rounded-t-xl"> </div> <div class="p-6 bg-white rounded-b-xl"> <h2 class="text-2xl">{{ item.name }}</h2> </div> </a> </div> {% endfor %} {% else %} <p>No recently viewed items.</p> {% endif %} </div> </div> What im getting is the response NO recently viewed items, so i guess is not entering in the for loop This is my views.py (not all views but the fundamental ones to understand the problem) def items(request): query = request.GET.get('query', '') category_id = request.GET.get('category', 0) categories = Category.objects.all() items = Item.objects.filter() if category_id: items = items.filter(category_id=category_id) if query: items = items.filter(Q(name__icontains=query) | Q(description__icontains=query)) print(f'Session Data: {request.session.get("recently_viewed", [])}') return render(request, 'item/items.html', { 'items': items, 'query': query, 'categories': categories, 'category_id': int(category_id) }) def recently_viewed( request, pk ): print('Entered in the recently_viewed') if not "recently_viewed" in request.session: request.session["recently_viewed"] = [] request.session["recently_viewed"].append(pk) … -
How to add tokens to the Django rest framework?
in my case i create login api ,when user enter thier details at that time token not generating.so give me a solutions. in my case i create login api ,when user enter thier details at that time token not generating.so give me a solutions. I create token , in behalf generaing token any user can access api -
Nginx and Gunicorn Static files not being found in my docker-compose django project even if logs show '125 static files copied to '/app/static''
I have set up my nginx folder, DOckerfile, .env, docker-compose.yml and entrypoint.sh files, and everything is running okay and im able to see pages as it should be. But the only problem is I cant load staticfiles. The Gunicorn container logs are showing "Not Found" and the nginx container is showing failed (2: No such file or directory). These are my configuration files: docker-compose.yml version: '3' services: marathon_gunicorn: volumes: - static:/static env_file: - .env build: context: . ports: - "8010:8000" nginx: build: ./nginx volumes: - static:/static ports: - "8012:80" depends_on: - marathon_gunicorn db: image: postgres:15 container_name: postgres_db restart: always environment: POSTGRES_DB: xxx POSTGRES_USER: xxx POSTGRES_PASSWORD: xxx volumes: - pg_data:/var/lib/postgresql/data volumes: static: pg_data:` entrypoint.sh #!/bin/sh # Apply database migrations python manage.py migrate --no-input # Collect static files python manage.py collectstatic --no-input # Start Gunicorn server gunicorn absamarathon.wsgi:application --bind 0.0.0.0:8000 # Django Dockerfile FROM python:3.8 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./absamarathon /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT [ "sh", "/entrypoint.sh" ]``` nginx/default.conf upstream django { server marathon_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { alias /static/; } # location /media/ { # alias /app/media/; # … -
Wagtail rich text block better revision diffing
Its possible to override how Wagtail compare page changes? Now its converting html to flat text but I want a better view when diffing. This is how wagtail do the diffing between texts: class RichTextFieldComparison(TextFieldComparison): def htmldiff(self): return diff_text( text_from_html(self.val_a), text_from_html(self.val_b) ).to_html() register_comparison_class(RichTextField, comparison_class=RichTextFieldComparison) -
Removing django admin panel content
algorithm: pbkdf2_sha256 iterations: 216000 salt: 7WW1Fr****** hash: dqMnCG************************************** Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form. how can i remove this portion or hide this i couldn't get the solution from any where -
django.db.utils.OperationalError: (2005, "Unknown server host 'db' (11001)")
Im trying to create a superuser for my django app using python manage.py createsuperuser but i keep getting an error message. Im using docker for my app alongside a pipenv and a connection is established whenever i run docker compose up -d --build for both the app and the db. settings.py is also properly configured and uses the db service as the HOST. However this is the error im getting when im running python manage.py createsuperuser after running the previous command: PS C:\Users\nawar\Desktop\uni\Uni\Modules\UWE_Modules\Y3\DESD\CW2\mlaas-g7> python manage.py createsuperuser Traceback (most recent call last): File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection self.connect() File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\db\backends\base\base.py", line 263, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\db\backends\mysql\base.py", line 247, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\MySQLdb\__init__.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2005, "Unknown server host 'db' (11001)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\nawar\Desktop\uni\Uni\Modules\UWE_Modules\Y3\DESD\CW2\mlaas-g7\manage.py", line 22, in <module> main() File "C:\Users\nawar\Desktop\uni\Uni\Modules\UWE_Modules\Y3\DESD\CW2\mlaas-g7\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\nawar\.virtualenvs\mlaas-g7-hyj7l3ZN\lib\site-packages\django\core\management\__init__.py", line 440, in … -
how to remove super admin from dropdown if user is login
Please help me. I have to remove the super user from form showing in frontend. Means when I am creating todo and I also choosing user, so super admin is also display in dropdwn so I didn't try anything because i dont know how to do it and i am using built user model -
Django Autocomplete Light, forward widget is not working
I have the following code: forms.py from dal import autocomplete, forward class AnalysisForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Analysis fields = ['method', 'database'] method_type = forms.ChoiceField(choices=[('', ' -- select an option -- ', 'A', 'B')], required=True)) database = forms.ModelChoiceField(queryset=Database.objects.all(), required=True, widget=autocomplete.ModelSelect2(url='database-autocomplete', forward=("method_type", ), attrs={'data-placeholder': 'Database ...', 'data-minimum-input-length': 1., }, ) ) views.py class DatabaseAutocomplete(autocomplete.Select2QuerySetView): # url: database-autocomplete def get_queryset(self): qs = Database.objects.all() print(self.forwarded) script_type = self.forwarded.get('method_type') print("SCRIPT CHOICE") print(script_type) if script_type is None: qs = Database.objects.none() What this code is doing is is that the form takes a value for method_type and database (which uses autocomplete). I would like database to access the value of method_type when running the autocomplete function but it is not being sent (notice how I am printing self.forwarded, but it is always empty). I have also produced some variations on the above method for example: forward=(forward.Field("method_type"), ) which did not work. I also used: forward=(forward.Const(42, "b"), ) to try and send anything which also failed. Am I missing anything? I would appreciate some help. -
How to serve a Svelte app frontend build in Django backend static?
The svelte app is normal svelte (not kit) with some routing. Build by npm run build into: /dist: /assets/index.js, /assets/index.css, index.html. I tried to follow this tutorial for React and expect it to have the same results. When accessed the serving path, it returns error In the project folder: views.py `from django.shortcuts import render def index(request): return render(request, 'frontend/index.html')` `urls.py` `urlpatterns = [ # path("authors/", include("authors.urls")), path("admin/", admin.site.urls), path("", include("api.urls")), # path('static/', serve, {'document_root': settings.STATIC_ROOT, 'path': 'frontend/index.html'}), path('index/', views.index, name='index'), ]` `settings.py` `STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/frontend/assets')]` -
Disable add of related record in Django admin
I would like to customize a Django 5+ admin view page. The model looks like this class Person tutor = models.ForeignKey("Person", on_delete=models.SET_NULL, null=True, blank=True) and consequently the edit page for Person has a drop down box to select from a list of already added persons to the database, and add and delete buttons. Is there a way to remove (or disable) these add and delete buttons so that only Persons added before can be selected used? But I do not want to disable adding Persons in general, I just want that it cannot be done through this button. -
Trying to require password on django allauth social login with google workspace
The basic question is how to go about requiring a user to put in their password when using google SSO. We have a few users who use the same device and don't want them to all be able to log in as each other. If I could require a password after a unit of time that would be okay, but I think I have set in workspace to require login after 12 hours already. Otherwise logging in with google works fine. It's just requiring some kind of re-authentication periodically that we need. Here is the basic setup on django SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } Have tried updating the login link to use action-reauthenticate {% provider_login_url 'google' action="reauthenticate" %} This forces the user to select their account but doesn't require a password. -
'ProgrammingError: column does not exist' in Django
I've been moving development of my website over to using Docker. I replaced sqlite as my database with postgresql then ran the command docker-compose exec web python manage.py migrate in my Docker environment. I also updated MEDIA ROOT and MEDIA settings in my settings.py file and updated mysite/urls.py. When I go to 127.0.0.1:8000/admin to the look at stored/uploaded files I get an error: Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (column human_requirementschat.alias does not exist LINE 1: SELECT "human_requirementschat"."id", "human_requirementscha... ^ ) was the direct cause of the following exception: File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/admin/options.py", line 688, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/admin/options.py", line 2065, in changelist_view "selection_note": _("0 of %(cnt)s … -
Django form.is_valid() is incorrectly returning false for a missing field
When I submit a form to update a task in my project, the is_valid function returns false, and on the page it says: Error! Please correct the following errors: Description: This field is required. But when I print the POST request into the console, the description field isn't required, and it does have data. this is the views.py function: def task_edit(request, task_id, slug): """ Display an individual task for editing. """ # Retrieve the task instance task = get_object_or_404(Task, pk=task_id) # Retrieve the job instance job = get_object_or_404(Job, slug=slug) if request.method == "POST": # Print out the request.POST dictionary to inspect the data print(request.POST) # Initialize form with task instance and data from request add_task_form = AddTaskForm(data=request.POST, instance=task) if add_task_form.is_valid(): # Save the form data to the task instance task = add_task_form.save(commit=False) task.job = job task.save() messages.success(request, 'Task Updated!') return HttpResponseRedirect(reverse('job_detail', args=[slug])) else: messages.error(request, 'Error updating task!') else: # Initialize form with task instance add_task_form = AddTaskForm(instance=task) and this is the JS function: // Handle click event for edit button $(".edit-button").on("click", function() { console.log("Edit Task button clicked"); var taskId = $(this).data("task_id"); var description = $(this).data("description"); var tradesRequired = $(this).data("trades-required"); var tradesmanAssigned = $(this).data("tradesman-assigned"); var timeRequired = $(this).data("time-required"); var isCompleted = …