Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Class inheritance python
In the case creating a model, for example class Student(models.Model) name=models.charfield(),roll=models.integerfield() similarly, In the case creating a form, class newform(forms.Form) name=forms.charfield(),roll=forms.integerfield() similarly, In the case creating a serializer, class serial(serializers.Serializer) name=serializers.charfield(),roll=serializers.integerfield() I understood that in each classes,a base class is inherited but i am confused that if different objects of different classes are created inside a class in each scenario then what is the meaning of inheriting models.model, forms.Form,serializers.Serializer what these inherited classes do? -
How to create a class and connect it with an existing table in Django?
I am new to Django, and I have a SQL Server database. I don't want to create a class and make a migration because I already have a table with its data. Migration will create a new table for the class. I want to create a class and connect it with the existing table in models.py. How can I do that? Here is my table: CREATE TABLE [dbo].[login]( [lo_id] [int] IDENTITY(1,1) NOT NULL, [lo_username] [nvarchar](50) NOT NULL, [lo_password] [nvarchar](max) NOT NULL, [lo_name] [nvarchar](50) NOT NULL, [lo_email] [nvarchar](50) NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] Here is the connection in the sittings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DjangoTest', 'USER': 'sa', 'PASSWORD': 'p@$$W0rd', 'HOST': 'HostName\\SQLSRV2019', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } -
Django DRF router reverse with kwargs
class API(ModelViewSet): @action(detail=True, methods=['post'], ) def invite_users(self, request, pk=None): chat_group = self.get_object() invite_users_url = reverse('group-detail', kwargs={'pk':group_id, 'format':'invite_users'},) I want path/pk/invite_users but I got NoReverseMatch: Reverse for 'group-detail' with keyword arguments '{'pk': 'SvY9aA1SK6ok', 'format': 'invite_users'} -
ERROR: No matching distribution found for GDAL==2.4.0 (Heroku/Django)
I have been troubleshooting this error for a long time and can't get my head around it. My app deploys over Heroku successfully but when I run it - it throws an Application Error. Consulting build output I see that GDAL Library is causing the issue (traceback below). I have tried to enable GDAL following the Heroku docs. My Aptfile contains: gdal-bin (as per the Heroku docs, as I understand them). I have tried manually setting the GDAL version in requirements.txt to GDAL==2.4.0, GDAL=3.4.1(latest version) and, following this SO answer, GDAL without a version attached. (requirements.txt) below. Requirements.txt: asgiref==3.4.1 beautifulsoup4==4.10.0 bs4==0.0.1 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.10 cryptography==36.0.1 defusedxml==0.7.1 dj-database-url==0.5.0 Django==4.0.1 django-allauth==0.47.0 django-bootstrap-modal-forms==2.2.0 django-heroku==0.3.1 django-on-heroku==1.1.2 django-widget-tweaks==1.4.11 djangorestframework==3.13.1 GDAL gunicorn==20.1.0 idna==3.3 oauthlib==3.1.1 psycopg2==2.9.3 psycopg2-binary==2.9.3 pycparser==2.21 PyJWT==2.3.0 python3-openid==3.2.0 pytz==2021.3 requests==2.27.1 requests-oauthlib==1.3.0 soupsieve==2.3.1 sqlparse==0.4.2 urllib3==1.26.8 whitenoise==5.3.0 Traceback from Heroku build-output [...] Collecting GDAL==2.4.0 Downloading GDAL-2.4.0.tar.gz (564 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-pnmrbd3c/gdal_00a97084715441d78d0780b0c9cd0780/setup.py'"'"'; __file__='"'"'/tmp/pip-install-pnmrbd3c/gdal_00a97084715441d78d0780b0c9cd0780/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-j_z5wzv2 cwd: /tmp/pip-install-pnmrbd3c/gdal_00a97084715441d78d0780b0c9cd0780/ Complete output (73 lines): WARNING: … -
How can a website be run without the user having the language it was built on installed
This refers to all languages. How is it that if I don't have for example Ruby on Rails or Django installed, I can open a website it was built on without having to download it? Because running the source code will definitely not work, so why does it work in a browser? -
Django with Google Cloud Storage
I have been trying to implement google cloud storage (media file uploads) for my django app on google app engine using the django-storages package. I have followed all the specification given by the package. I also set the relevant policies and roles for the service account to access the storage bucket but I keep getting the error "anonymous caller does not have storage.objects.get access to the google cloud storage object." when trying to view the images in my html template. I can only view the images in the template when I include the permission for allUsers in storage bucket settings. Does anybody know how to fix this issue without making your bucket publicly accessible. This is the screenshot of my configuration for django-storages in the settings.py file -
Cutting video using moviepy in Django
How can I set video duration like TikTok.com. I don't a user to upload a video that is more than 3 minutes or 4 minutes using moviepy in django. how can i cut the video. This is my views: From Moviepy.editor import * def addvideo(request): if request.method == 'POST': file = request.FILES.get('video') videos = Video.objects.create( file=file ) return redirect('home') return render(request, 'addvideo.html') -
Using python manage.py migrate --check in kubernetes readinessProbe never succeeds
I have a django deployment on kubernetes cluster and in the readinessProbe, I am running python manage.py migrate --check. I can see that the return value of this command is 0 but the pod never becomes ready. Snippet of my deployment: containers: - name: myapp ... imagePullPolicy: Always readinessProbe: exec: command: ["python", "manage.py", "migrate", "--check"] initialDelaySeconds: 15 periodSeconds: 5 When I describe the pod which is not yet ready: Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 66s default-scheduler Successfully assigned ... Normal Pulled 66s kubelet Successfully pulled image ... Normal Created 66s kubelet Created container ... Normal Started 66s kubelet Started container ... Warning Unhealthy 5s (x10 over 50s) kubelet Readiness probe failed: I can see that migrate --check return 0 by execing into the container which is still in not ready state and running python manage.py migrate echo $? 0 Is there something wrong in my exec command passed as readinessProbe? -
Django admin: order by a nullable date, with null values at the end
I have a model with a DateTimeField which I would like to use to order the table in admin. Using ordering = ('-completed',) in admin.py works, but those with null values come first in the sort. Is there a way to make them appear at the end instead? So at the moment I have something like: Column A Completed Column C x - y x - y x Today's date y x Yesterday's y Is there a way to make it like this? Column A Completed Column C x Today's date y x Yesterday's. y x - y x - y -
Websocket connection is failed [env: django channel, gunicorn, uvicorn, nginx, postgre and redis over https(wss)}
I have deployed my app on digitalOcean using this tutorial link ,https and all pages rendering properly and django working fine, The issue right now is websocket connection is failed, the error messages I got are from console web page says: WebSocket connection to 'wss://mysitedomain/ws/chat/2_3/' failed: Other error message from gunicorn server shows 404 not found page: "GET /ws/chat/2_3/ HTTP/1.0" 404 Regardless what wss configuration I add it to nginx configuration file; connection is failed!!.. below is mysite configuration file under 'etc/nginx/sites_available' folder in linux for your reference ( I have removed all wss configuration blocks): please note I already have installed uvicorn[standard] version but didn't help!! server { listen 80; server_name IP domain name; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/DjangoProject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django include template tag include multiple context object
I`m building a blog template page, which will include the Post list context object and the Category list context object. I`m using class-based view in the views.py: class CatListView(ListView): model = Category context_object_name = 'categories' template_name = 'blog/category.html' class PostListView(ListView): model = Post context_object_name = 'post_list' template_name = 'blog/blog.html' urls.py: urlpatterns = [ path('', views.PostListView.as_view(), name='blog'), ... ] using the include tag to include the category template in blog.html: {% extends 'base.html'%} {% block content %} <main class="main-content"> <div class="container mt-8"> <div class="row"> <div class="col-lg-8"> <h2>Post list</h2> {% for post in post_list %} {{ post.title }} {% endfor %} </div> <div class="col-lg-4"> {% include "blog/category.html"%} </div> </div> </div> </main> {% endblock %} category.html: <ul class="mt-8"> {% for cat in categories %} <li>{{ cat.title }}</li> {% endfor %} </ul> I just cant pass the category context in the post.html template. maybe Im can do it with the function-based view, but is it possible to pass multiple contexts into one template using only a class-based view? -
Django ReactJS - Exposing multiple graphql endpoints
I am building a web app using Django backend and ReactJS frontend. This web app will be a culmination of several smaller applications like Todo app, Investments Tracker, Budget Analysis etc. Frontend: This I how I have structured the frontend (ReactJS project): src - apps - Home - index.jsx - Todo - index.jsx - Expenses - index.jsx - Investments - index.jsx - index.js - App.jsx App.jsx function App() { return ( <Routes> {/* COMMON ROUTES */} <Route path="/todos" element={<Register />} /> <Route path="/activate/pending" element={<PendingActivation />} /> <Route path="/activate" element={<Activate />} /> <Route path="/login" element={<Login />} /> {/* APP ROUTES */} <Route path="/todos" element={<Todo />} /> <Route path="/expenses" element={<Expenses />} /> <Route path="/investments" element={<Investments />} /> </Routes> ); } function AppWrapper() { return ( <Provider store={store}> <BrowserRouter> <Alerts /> <App /> </BrowserRouter> </Provider> ); } ReactDOM.render(<AppWrapper />, document.getElementById('root')); Based on the endpoints, I will route the User to one of the sub-apps. Backend: And this is how I structured my backend (Django project): backend - app # project - settings.py - base # app 0 - has custom User model - todo # app 1 - to maintain todo list - expenses # app 2 - to maintain budget - Investments … -
Styling a checkbox in django template
I have a file (bs4_form.html) that handles my django form, that i just include in my html template (contest_form.html), but for some reason my checkbox isn’t displaying well… bs4__form.html {% load widget_tweaks %} {{ form.media }} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} {% for field in form.visible_fields %} <!----> <div class="row"> <div class="col-12"> <div class="mb-1"> <!----> <div class="form-group"> {% render_field field.label_tag %} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} <div> {% render_field field class="form-control" class="is-valid" %} </div> {% endif %} {% else %} <div> {% render_field field class="form-control" %} </div> {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> <!----> </div> </div> </div> <!----> {% endfor %} contest_form.html {% extends 'contest/base.html' %} {% load static %} {% block content %} … <!----> <form method="post" enctype="multipart/form-data" novalidate> {% csrf_token %} {% include 'contest/bs4_form.html' with form=form %} <button type="submit" class="btn … -
Django - Accessing the same view with complex lengthy algorithm by several users in the same time
I am trying to implement an anonymous chat web application in Django. Right now I am on the stage where I need to connect users with each other based on their preferences, location etc. So I have a view find_room(request), where I am executing lengthy algorithm which runs for a few seconds, trying to find the closest user who is also searching for other users using the same view. So my problem is that when one user is calling the find_room view and then the other user calling the same view, then the second user should wait until first users's call is ended. So basically I need this view to be executed as a separate thread, so that several users can call this view and use this searching algorithm in the same time. Is there any functionality inside django that can help me? Or are there any other technologies I should use? (I heard about celery, but not sure if this is right thing for my purposes). Sorry if the question is confusing, and thanks for the answers! -
My registered accounts in herokuapp is not shown in django admin
I have created a django app and deployed it in Heroku. The web app works fine and the user registration and login works too. But when I open the django admin site it doesn't show the latest registered account. I have asked a few people to test my system so surely, there will be a few new accounts but the only accounts there were the ones I tested with a dummy account before deploying in heroku. This is my admin.py from django.contrib import admin # Register your models here. settings.py """ Django settings for sentiment_emotion_analysis project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sentiment.settings") # import django # django.setup() # from django.core.management import call_command from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.DEBUG: 'alert-debug', messages.INFO: 'alert-info', messages.SUCCESS: 'success', messages.WARNING: 'alert-warning', messages.ERROR: 'danger', } # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'g&x!0fjh8c8)e_-z@gs1^lbngvqwk2(o3s(5zg!o&woxdsu_un' # SECURITY WARNING: don't … -
django and gurobi in docker have permission issues
I am trying to create a docker image for Django + Gurobi. Container runs as root by default. Gurobi does not want to run as root since license is issued to non-root user. If switching to non-root, Django's python complains "attempt to write a read-only database" using /db.sqlite3. chown+chmod just /apps, /db.sqlite3, and /usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3 did not help. problem seems to go away if I chown and chmod 777 the entire container: bad idea What is the solution? Below is the Dockerfile FROM python:3.9 COPY . . ADD data . # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV APP_USER=user32 ENV APP_HOME=/home/$APP_USER # install python dependencies RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --upgrade pip RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --no-cache-dir -r requirements.txt RUN apt-get update && apt-get install -y inetutils-ping RUN tar xvzf gurobi9.5.0_linux64.tar.gz ENV GUROBI_HOME /gurobi950/linux64 RUN cd /gurobi950/linux64 && python setup.py install RUN rm gurobi9.5.0_linux64.tar.gz RUN groupadd -r $APP_USER && \ useradd -r -g $APP_USER -d $APP_HOME -s /sbin/nologin -c "Docker image user" $APP_USER ENV TZ 'America/Los_Angeles' RUN echo $TZ > /etc/timezone && apt-get update && \ apt-get install -y tzdata && \ rm /etc/localtime && \ ln -snf /usr/share/zoneinfo/$TZ … -
Features in django project
I have made a summary generation project using django. I need help with some of the feature such as adding bulk data in database using a form. and displaying multiple querysets in a single html table. Can anyone help me with this? -
django template not rendering folder images
here is my code bellow. views.py def galerry(request): result = request.GET.get('folder') print(result) imageList = [] directory = settings.MEDIA_ROOT for file in os.listdir(directory+"images/"): filename = os.fsdecode(file) if filename.endswith(".jpeg") or filename.endswith(".png"): src = os.path.join(directory, filename) imageList.append(src) print(filename) json_object1 = json.dumps(imageList) print(type(json_object1)) response = json.loads(json_object1) print(type(response)) print("json conversion", json_object1) return render(request, "galerry.html", context={'json_object1': response}) The loop worked fine i got all the files in the folder using print function but the image link seems not found in djando template. galerry.html file {% for item in json_object1 %} <img src="{{item}}" alt="test" height="200"> {% endfor %} settings STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_root") MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "gallery/static_cdn/") im getting Not Found: /Users/joejoe/Desktop/Gallery/gallery/static_cdn/05.jpeg [15/Jan/2022 04:57:05] "GET /Users/joejoe/Desktop/Gallery/gallery/static_cdn/01.jpeg HTTP/1.1" 404 1828 thanks will appreciate your help -
Add new update delete edit is not working
In this project, add new, edit, delete and update is not working. The code is correct but when I click submit, update It is not working. Please tell me Where I got wrong. Please tell me. urls.py: from django.contrib import admin from django.urls import path from master import views from django.conf.urls.static import static from mysite6 import settings urlpatterns = [ path('admin/', admin.site.urls), path('control/', views.controlindex), path('controladdnew',views.controladdnew), path('controledit/<int:id>', views.controledit), path('controlupdate/<int:id>', views.controlupdate), path('controldelete/<int:id>', views.controldestroy), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py: from django.shortcuts import render,redirect from django.http import HttpResponseRedirect from master.forms import ControlmachineForm from master.models import Controlmachine # Create your views here. def control(request): if request.method == 'POST': form = ControlmachineForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['control_uploadfile']) model_instance = form.save() model_instance.save() else: form = ControlmachineForm() controlmachiness = Controlmachine.objects.all() return render(request,'master/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def handle_uploaded_file(f): with open('master/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def controladdnew(request): if request.method == "POST": form = ControlmachineForm(request.POST) if form.is_valid(): try: form.save() return HttpResponseRedirect('/control/') except: pass else: form = ControlmachineForm() return render(request,'master/control_index.html',{'form':form}) def controlindex(request): controlmachines = Controlmachine.objects.all() return render(request,"master/control_show.html",{'controlmachines':controlmachines}) def controledit(request, id): controlmachine = Controlmachine.objects.get(id=id) return render(request,'master/control_edit.html', {'controlmachine':controlmachine}) def controlupdate(request, id): controlmachine = Controlmachine.objects.get(id=id) form = ControlmachineForm(request.POST, instance = controlmachine) if form.is_valid(): form.save() return HttpResponseRedirect('/control/') return render(request, 'master/control_edit.html', {'controlmachine': controlmachine}) def controldestroy(request, id): controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() … -
Url contains improper value
How would I pass the relative url from the page I came from. url.com/calendar -> click editprofile -> it does url.com/editprofile//calendar -> where I needed url.com/calendar urls.py path('editProfile/<str:page>/', editProfile, name='editProfile'), html: {% block content %} <form method = "POST" action='editProfile/{{request.get_full_path}}/' enctype="multipart/form-data"> {% csrf_token %} {{ editProfileForm.as_p }} <input type="submit" name="editProfileForm" value="Upload"> </form> {% endblock %} views.py @login_required @require_http_methods(["POST"]) def editProfile(request,page): context={} editProfileForm = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user) # Rework this to get url and then set nmenu to that value print(page) if page =='': context['nmenu']='home' else: context['nmenu']=page if editProfileForm.is_valid(): editProfileForm.save() editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm context['is_post'] = False return render(request, "home.html", context) else: context['is_post'] = True context['editProfileForm'] = editProfileForm return render(request, "home.html", context) -
Is it possible to MOVE items in a database in django without deleting them?
I have a simple model in Django for a Library Manager. Inside there are 3 models. One to record all the books, another to issue the books and the last one to return the issued books. I already have the relationships done, but the problem arose when I wanted to issue a book. If a book is issued it should no longer be in the book records but rather be in the issued records. And when it is being returned it should go through the return class and get added to the book record. My question is "is it possible to move books in my case from on class to another?" -
Url and Path Issues in Django
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('register`enter code here`, views.register, name='register'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('post', views.post, name='post'), path('postpage/<str:pk>', views.postpage, name='postpage'), ] -
HTML file in live mode in visual studio code?
My HTML file is in live mode. I cannot edit it and have to make modifications externally in notepad. Anyone can help me out? -
Not enough values to unpack error in production only
I recently launched my app on Heroku. When I run my app locally it works fine and I get no errors. For context, I recently switched my database from sqlite to PostgreSQL. When I run the app on Heroku I get the following ValueError. What could be causing this error to only occur in production and not locally? Traceback Environment: Request Method: POST Request URL: https://myurl.herokuapp.com/ Django Version: 3.2.10 Python Version: 3.9.9 Installed Applications: ['PRIIIME_Travel.apps.PriiimeTravelConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/PRIIIME_Travel/views.py", line 132, in get_ranking result1, result2, result3, result4, result5 = first_5_results_list Exception Type: ValueError at / Exception Value: not enough values to unpack (expected 5, got 0) views.py # list of each variable's broad category broad_variable_list = ["safety", "affordability", "transit", "language", "attractions", "climate"] # weighting of each variable ranking weight_variable1 = 0.33 weight_variable2 = 0.24 weight_variable3 = 0.17 weight_variable4 = 0.14 weight_variable5 = 0.12 def get_ranking(request): # if this is a POST request we need to process the form data if request.method … -
Django Forms: Default Value in get request
I am building a personal finance site that displays monthly transaction information on the homepage. I want the user to be able to switch months via a dropdown. Thankfully I already have the code built to filter on transaction date, what I am having trouble with is displaying a default value in the dropdown. The dropdown is populated by a dictionary (month_year_select) as you can see in forms.py below. I am not getting any error messages, the application just isn't performing the way I need. My question is how do I get the current month (Jan, 2022) to display by default in the dropdown when the user navigates to the homepage? The page already displays the current month's data, but the dropdown just lists the most recent month. I have looked through a ton of posts on this and the one that seems to have the closest explanation to what I need is here django forms: default values for bound forms I realize the views.py code is messy, I apologize in advance. I am new to python and would really appreciate any help you have to offer. Let me know if you need further explanation/other code examples. Thanks! python version …