Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do two separate Stripe payments with one click
I'm looking for a way to split a Stripe payment into two with one click, but one of the installments should be automatic while the other is based on a condition. I'm new to the Stripe API and relatively new to Django as well. It looks like Stripe Connect would solve the issue of splitting the payment in two, but both installments would be triggered at the same time which I'm trying to avoid. I know this is a pretty vague question so I apologize in advance. But if anyone has an idea how I could implement this please let me know! Thanks -
how can i add two related nested instance in one request using DRF?
Hi I'm new to Django rest framework I have class Location(models.Model): name = models.CharField(("name"), max_length=50) long = models.CharField(("longitude"), max_length=50) lat = models.CharField(("latitude"), max_length=50) def __str__(self): return self.name class Farm (models.Model): name = models.CharField(("Name"), max_length=50) size = models.FloatField('Size') size_unit = models.CharField(("Size Uint"), max_length=50) owner = models.ForeignKey(Account, on_delete=models.SET('Deleted user')) location = models.ForeignKey(Location, on_delete=models.SET('Deleted Location')) def __str__(self): return self.name those are my model and here are my serializers class FarmSerializer(serializers.ModelSerializer): class Meta: model = Farm fields = '__all__' class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = '__all__' how can I create both Farm and location in one request like { "name": "new farm", "size": 400, "size_unit": "meter", "owner": 1, "location":[{ "name":"new location", "long":2132.123212, "lat":2213231.1234}] } I tried to add create at serializer like def create(self,validated_date): location_data = validated_date.pop('location') location = Location.objects.get_or_create(**location_data) farm = Farm.objects.create(**validated_date,location=location) return farm but it does not work and it gives me this message { "location": [ "Incorrect type. Expected pk value, received list." ] } thanks for help -
Unable to serve static file in Django deployed to production in Digital ocean
currently I deployed my django app in Digital ocean droplet.In localhost it works well but it cant serve js/css files in static folder when deployed to prod, after some googling possible solutions, nothing works for me. server { server_name keywordprocessor.prodsite.com www.keywordprocessor.prodsite.com> location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/projects/backend/crawler; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } ..... BY digital oceans default, the project resides inside root directory `cd projects` `pwd` returns /root/projects/ Settings # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(BASE_DIR, "/") THis is how the project folder looks like backend/ crawler/ static/ templates .gitignore requirements.txt /etc/systemd/service/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/root/projects/backend/crawler ExecStart=/usr/local/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ crawler.wsgi:application [Install] WantedBy=multi-user.target All js and css files cant be served `Failed to load resource: the server responded with a status of 404 (Not Found)` It does load the page but css messed up Regards -
How can I add ordering for ManyToMany field?
I have two models: CustomUser and AgreementReglament At this moment relation between the models looks like this: class AgreementReglament(models.Model): name = models.CharField(max_length=32) # just name of the reglament approvers = models.ManyToManyField( # set of users to approve 'CustomUser', related_name='agreement_reglaments' ) How can I set order of approvers (e.g. CustomUser1 should be the first in particular AgreementReglament1, CustomUser2 should be second and so on, but in AgreementReglament2 CustomUser2 can be the first) I think that json data should be like this: { "name": "Reglament1", "approvers": [ { "approver_name": "Alex", "approver_order": 1, }, { "approver_name": "Bob", "approver_order": 2, } ] } -
Adding markdown highlighted fenced block to django app with markdonx
I have been looking through the documentation but I can’t seem to get this to work. I wish to publish posts from a “creation page”. I want to use the editor markdownx. I got it to work, however there is no “fenced code support”. I tried to add the following line of code to my settings.py MARKDOWNX_MARKDOWN_EXTENSIONS = ['fenced_code'] but it breaks the code, in fact I get the following error (when I try to create a post): SyntaxError at /markdownx/markdownify/ if I erase the extensions list, it works fine. I would like also to use the codehilite extension by adding it to the list like this MARKDOWNX_MARKDOWN_EXTENSIONS = ['fenced_code' ,'codehilite'] but it does not work. I have installed pigments but the documentation does not seem to help. Could someone help me add this extensions correctly, getting highlighted code blocks to work. Thank you very much. -
Django Rest-Framework search-fields wont work inside @action
I'm trying to use the search field offered by DRF inside of an action, but it seems to not work. I had a similar problem paginating inside of the action but found a solution. My guess is that it's overriding the ModelViewSet so I have to manually add the filtering, but is there a way to use the same search_fields offered by DRF. Here's my code: class XViewSet(ModelViewSet): queryset = X.objects.all() serializer_class = XSerializer permission_classes = [IsAdminUser] filter_backends = (SearchFilter,OrderingFilter) search_fields = ['a','b','c','d'] @action(detail=False, methods=['GET'], permission_classes=[IsAuthenticated]) def me(self, request): query = X.objects.filter(ex_id=request.user.id) if request.method == 'GET': serializer = XSerializer(query, many=True) return Response(serializer.data) Any help is appreciated, Thank you :) -
Problem to install django proyect in IIS server windows 2016
I need help with the following problem: raise RuntimeError('No Apache installation can be found. Set the ' RuntimeError: No Apache installation can be found. Set the MOD_WSGI_APACHE_ROOTDIR environment to its location. This appears the moment I try to run the server the file. This is the content of the web.config file: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Proyectoqr" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python35\python.exe|C:\Python35\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\proyectoqr"/> <add key="WSGI_HANDLER" value="proyectoqr.wsgi.application"/> <add key="DJANGO_SETTINGS_MODULE" value="proyectoqr.settings"/> <add key="APPLICATION" value="get_wsgi_application()"/> </appSettings> </configuration> This is the settings file of the project import os from pathlib import Path from telnetlib import LOGOUT from django.urls import reverse_lazy BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ALLOWED_HOSTS = ['10.100.10.133', 'localhost', "127.0.0.1:8000", '127.0.0.1' ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'import_export', "apps.equipo", "apps.usuariof", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'proyectoqr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend', ] WSGI_APPLICATION = 'proyectoqr.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { … -
error in migration with legacy database in Django
I'm working on creating a filter in django where the options displayed are coming from a new column in the database. It turns out that this column was created directly in the database and so that it could be displayed in my template, I need to capture this field in the models. After some research, I found in django's own documentation a function called "inspectdb" that is called by manage.py. So far so good, after executing the function, the database fields are added to my project so that they can be directed to their corresponding app.models. The documentation indicates that I must perform a python manage.py migrate for the sync to complete, this snippet of code is where the problem happens. When performing the migrate, I get the following error: "django.db.utils.ProgrammingError: relation "crontabmanager" already exists" The "crontabmanager" table actually exists in my database, but it is not changing at this time. Some actions were taken to try to get around this problem, for example: I tried to ignore the migration and use the new field directly in the system, but it returns stating that the new column does not exist Delete the migration file and create a new "makemigration" Delete … -
Use Facebook and Google social login urls only in django all auth
For normal signin/signup i'm using django's default singin/signup, but in facebook and google login i'm using django allauth, and to implement django allauth i have to add all its urls by adding: path('accounts/', include('allauth.urls')), But i don't need all the allauth urls, i only need the ones that are related to facebook and google social login. So how do i add only the ones that are needed for facebook and google login to run i tried this: path("accounts/", include("allauth.socialaccount.providers.google.urls")), path("accounts/", include("allauth.socialaccount.providers.facebook.urls")), With these two lines Google login worked normally but facebook login worked at first steps but the last step where i'm redirected to /accounts/facebook/login/callback/?code=xxxxx... it returns error 500 I'm pretty sure the login was implemented correctly and the problem is in adding the needed urls because everything works normally when using include('allauth.urls') -
How to separate tables based on the model using FSM and FSM-Log?
I'm currently logging status changes to several models in my Django REST API using the django-fsm and django-fsm-log packages. However, all of the logs are stored in a single table. This is gonna end up being a massive table that will take time to run through to do analysis and reporting. To make it easier I'd like to either break out the logging table by each individual model or sort them by the highest level model that's associated. I'll explain what I mean. I have 3 models: class Status: CREATED = 'created' ACTIVE = 'active' CANCELLED = 'cancelled' COMPLETED = 'completed' STATUS_CHOICES = ( (Status.CREATED, 'Created'), (Status.ACTIVE, 'Active'), (Status.CANCELLED, 'Cancelled'), (Status.COMPLETED, 'Completed'), ) # model 1 #========= class Company(models.Model): name = models.CharField(max_length=255) # model 2 #========= class Order(models.Model): name = models.CharField(max_length=255) company = models.ForeignKey(Company, related_name='company_order', on_delete=models.CASCADE) current_status = FSMField(choices=STATUS_CHOICES, default=Status.CREATED) @fsm_log_by @fsm_log_description @transition(field=current_status, source=Status.CREATED, target=Status.ACTIVE) def order_created_to_active(self, by=None, description=None): return "order is now active" @fsm_log_by @fsm_log_description @transition(field=current_status, source=Status.ACTIVE, target=Status.COMPLETED) def order_active_to_completed(self, by=None, description=None): return "order has been completed" @fsm_log_by @fsm_log_description @transition(field=current_status, source=Status.ACTIVE, target=Status.CANCELLED) def order_active_to_cancelled(self, by=None, description=None): return "order has been cancelled" # model 3 #========= class Sale(models.Model): sale_amount = models.DecimalField(max_digits=19, decimal_places=4) description = models.CharField(max_length=1000) company = models.ForeignKey(Company, related_name='company_sale', on_delete=models.CASCADE) … -
how to add data to database in django
I send the data I get from websocket with javascript to the view.py section of python-django with var xhr = new XMLHttpRequest() ///. my question is; The data comes to view.py. How can I save this incoming data to the database from now on? views.py; def gelismis_alim(request): data = json.loads(request.body) front_end_adet = data.get('adet') //I know probably,I should write here something to add it to database but I don't know what it is. print(data) return HttpResponse('/')enter code here the data which sended with js to django, stored in front_end_adet variable.this data is static, not change everytime. When I take a data from websocket I store it in a variable then I send it django view for once. my model.py; class AL(models.Model): quant = models.CharField(null=False) price = models.CharField(null=False) class SAT(models.Model): quant = models.CharField(null=False) price = models.CharField(null=False)enter code here What I want is to add the data in the front_end_piece variable to the quant part of the AL table.I would be glad if you help thank you. -
I'm trying to return mutliply queryset
I have endpoin called groups I want to return to each user groups that he created and the groups that he member in it my model class Group(models.Model): title = models.CharField(max_length=100,blank=False,default='') project = models.ForeignKey('Project',related_name='groups',on_delete=models.CASCADE) owner = models.ForeignKey('auth.User',related_name='group',on_delete=models.CASCADE) member = models.ManyToManyField('auth.User',related_name='group_members') created = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return self.title here is my serializer class GroupSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Group fields = ('url','title','owner','member','created','active','project',) here is my view class GroupViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = ( permissions.IsAuthenticated,) def get_queryset(self): queryset = self.queryset query_set = queryset.filter(owner=self.request.user) query_set1 = queryset.filter(member=self.request.user) return list(chain(query_set)) + list(chain(query_set1)) def perform_create(self, serializer): serializer.save(owner=self.request.user) this view work with me but in the Group Instance return "detail": "Not found." here is my urls router = DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'projects', views.ProjectViewSet) router.register(r'tasks', views.TaskViewSet) router.register(r'groups', views.GroupViewSet) # The API URLs are now determined automatically by the router. # Additionally, we include the login URLs for the browsable API. urlpatterns = [ re_path(r'^', include(router.urls)) ] sorry my english is not good at all hope you understand me and hope you to help me thanks -
How to convert a view to a pdf in Django?
I need to render PDF files dynamically in a Django web app. I understand there are 2 options : Render an html template file then convert it to a PDF file. Convert a webpage into a PDF file directly How to do this? Any solution specifically made for Django? -
Is there any solution to fix this Cors error?
I have made an api from django but when I call from my react app It gives CORS error my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ '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', 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", ] enter image description here -
Extract multiple start date and end date from a string in python?
I am making a resume parser but I want to know the years of experience of the person from the experience section and want results like if there are 3 years of experience is mentioned and there are 3 companies the person worked in those 3 years and there are the start and end date mentioned on all of them so is there any way to know this is the start date and this is an end date and also can I calculate the total years of experience mentioned in the experience section by adding all those ranges. Example field Experience AI and Machine learning Intern, Dawn DigiTech (04/2022 -present), ❖, This company digitally transform multiple front- and back-office business, processes, SCM, ERP and Manufacturing Excellence., -, SpiceJet(08/2020 - 10/2021), ❖, Leading Indian airlines company worked and Developedy of 30%, Machine learning Intern, TutorBin(02/2022 - 05/2022 ), ❖, Tutorbin is an integrated online tutoring platform serving as a one-stop, solution for students and online tutors. work on Ai and Machine learning, tasks provided by the client, 60%, This is the parsed experience section so in this I want to extract dates ranges which should know the start date and end … -
How to get VScode Integrated Terminal Virtual Environment working?
I have completed a few courses online in Python and recently started a new course in Django. Previously I always used a virtual environment but would activate the environment myself, but in the course I am working through via Code with Mosh he shows a way to have VSCode activate the environment automatically in the terminal. I tried to follow along but am having a hard time getting this to work. First I tried following Mosh’s steps by locating the virtual environment location in terminal on the Mac using: pipenv --venv and this returned the location as /Users/lewpiper/.local/share/virtualenvs/storefront-7UYLLetM on my Mac. I then tried to to use this in the command palette with bin/python on the end of the path in VSCode to select the python interpreter and it didn’t seem to work. It seems like it didn't create the VSCode folder or JSON file that I saw in the lessons I was watching. Then I tried to edit the workspace settings in VSCode and add the following "python.pythonPath": "/Users/lewpiper/.local/share/virtualenvs/storefront-7UYLLetM"to match the VSCode file structure and again I am running into it not launching the terminal window with the virtual environment activated. Now when I click play in VSCode I … -
Button to hide contents of divs does not work in Django project
I have a javascript file with the following function: function sw(cl, v) { var a = document.getElementsByClassName(cl); for (var i=0; i<a.length; i++) a[i].style.display = v; } In my html file there is the following code: <script src="sw.js"> </script> <button onclick="sw('c1', ''); sw('c2', 'None'); sw('c3', 'None');">show c1</button> <button onclick="sw('c1', 'None'); sw('c2', ''); sw('c3', 'None');">show c2</button> <button onclick="sw('c1', 'None'); sw('c2', 'None'); sw('c3', '');">show c3</button> <div class="c1"> <!-- content --> </div> <div class="c2"> <!-- content --> </div> <div class="c3"> <!-- content --> </div> I tried using the function in a separate html file and it works, so do the buttons. However, I tried using that in a Django project and the buttons do not work. The mouse cursor does not change when I hover over a button but the button's color changes. The divs contain Django commands such as {% include "file.html" %}. Why won't the code work properly in the project? For context, I am trying to write a User Interface selector. The buttons are supposed to change what style is displayed. -
Flask print dict in jinja template with multiple values
I have a python/dict/flask/jinja printout problem with a dict containing multiple values. Basically. specialDict = {} specialDict[key]= Value printing it with {% for key, Value in specialDict.items() %} <a href=story/{{Value}}> <p class="fs-6 1h-1"> {{ key }} </p> </a> </ul> {% endfor %} works fine. BUT newspecialDict = {} newspecialDict[key]= Value1,Value2,Value3 printing it with the same code {% for key, Value in newspecialDict.items() %} <a href=story/{{Value}}> <p class="fs-6 1h-1"> {{ key }} </p> </a> </ul> {% endfor %} fails with KeyError : "('value1'," which is close but not "value1" . I understand flask/jinja is trying to unroll something and fails. Since for some reason python accepts dicts with multiple values even if the internet says its always just pairs of key, value (just one) there must be a way to print all the values in the template as part of the loop. tried and failed with unexpected {%: ... {% for key, value in newspecialDict.items() %} {% for innervalue in value.items() %} ... -
The new url id is getting appended after the previous request's url
I'm making a get request in django using html form as: crud.html <form action="{% url 'crudId' id %}" method="get"> <div class="col"> <div class="form-group" style="width: 20%;margin-top: 5px"> <label for="name">Id</label> <input type="number" name="id" value="{% if data %}{{ id }}{% endif %}"> </div> <input type="submit" value="OK" style="width: 30%; margin-left: 40%"> ... my view for this: class CrudPageView(View): def get(self, request, id=1): # get the id from the page oid = id ... # some data and operation ... return render(request, 'crud.html', {'data': data, 'id': oid}) and in urls.py as : path('crud/', CrudPageView.as_view(), name='crud'), path('crud/id=<int:id>', CrudPageView.as_view(), name='crudId') ... so http://localhost:8000/crud/ does work as intended and shows the page with data of id = 1; when I input any id, it also works as intended and shows the data for that id, but the url is in the form http://localhost:8000/crud/id=1?id=5 and after another input it will be http://localhost:8000/crud/id=5?id=12 What am I doing wrong? -
How to solve (unix:/home/richard/www/firstsite.sock failed (13: Permission denied) while connecting to upstream)?
I am trying do do this tutorial in a CentOS 7: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-centos-7 I want to test a Django basic project with Nginx, uWsgi into a CentOS 7. But in the browser results this error: 502 Bad Gateway nginx/1.20.1 Error502 firstsite.ini [uwsgi] project = firstsite username = richard base = /home/%(username) chdir = %(base)/%(project)/Documentos/desenvolvimento/nginxteste/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 uid = %(username) socket = /home/richard/www/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true uwsgi.service [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/usr/bin/bash -c 'mkdir -p /home/richard/www/; chown richard:nginx /home/richard/www/' ExecStart=/usr/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target nginx.conf # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 4096; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { listen 80; server_name … -
Populate data in pdf using django
I have to show a certificate in modal with the 2 option print and email. Certificate is pdf file i just need to fill two fields in the certificate user name and course name (which is coming from backend) how can I implement this in django? -
I cant donwload complete genome of Culex pipiens pallens of the ncbi by api(Entrez) : HTTP Error 400: Bad Request
I am a DawBio student, here is my question. Hola soy un estudiante de Dawbio aqui les va mi pregunta. I put you in a situation, I am trying to download the genbank if possible of the complete genome of Culex pipiens pallens from the ncbi but I get this error. the url of de ncbi. In the db variable that I sent in the fetch I already tried with nucleotide, genome, Gen etc. I thought that with assembly I would download it but no. When I run the download_genbank() function, I get the error: HTTP Error 400: Bad Request Los pongo en una situación, estoy tratando de descargar el genbank si es posible del genoma completo de Culex pipiens pallens del ncbi pero me sale este error. en la variable db que envio en el fetch ya probe con nuclotide, genome, Gen etc. pense que con assembly me lo descargaria pero no. Cuando ejecuto la función download_genbank(), aparece el error: HTTP Error 400: Bad Request this is the page: ncbi culex pipiens pallens complete genome from pathlib import Path from Bio import Entrez from Bio.Entrez.Parser import DictionaryElement, ListElement from Bio import SeqIO from Bio.SeqRecord import SeqRecord from typing import … -
Bootstrap tabs doesn't work with Django include option
I am working with bootstrap tabs in Django on page ps_tabs_capacity.html which extends the base.html . Inside ps_tabs_capacity.html there is tab I include another ps_capacity1.html which should display Charts.js charts with info from external database . ps_tabs_capacity.html: {% extends 'app_sins/base.html' %} {% load static %} {% block main%} <body style="background-color:RGB(244,246,249)" > <div class="container-fluid"> <br> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-bs-toggle="tab" href="#home">Home</a> </li> <li class="nav-item"> <a class="nav-link" data-bs-toggle="tab" href="#menu1">GnGp</a> </li> <li class="nav-item"> <a class="nav-link" data-bs-toggle="tab" href="#menu2">Menu 2</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div id="home" class="container tab-pane active"><br> </div> <div id="menu1" class="container tab-pane fade"><br> <h3>Menu 1</h3> {% include 'app_sins/ps_capacity1.html' %} </div> <div id="menu2" class="container tab-pane fade"><br> <h3>Menu 2</h3> </div> </div> </div> </body> {% endblock main%} in views.py I use two function (there are others, but not important here) ,first one is: def index(request): cursor1=connections['default'].cursor() cursor1.execute(attach) r1=dictfetchall(cursor1) ############################################################################### cursor2=connections['default'].cursor() cursor2.execute(gngp_ntp) r2=dictfetchall(cursor2) return render(request,'app_sins/ps_capacity1.html', {"all_post" : r1,"jokso" : r2}) and second one is: def ps_tabs_capacity(request): return render (request,'app_sins/ps_tabs_capacity.html', {} ) in url.py there are: path('sins/ps_tabs', views.ps_tabs_capacity, name='ps_tabs1'), path('sins/', views.index, name='index'), If I use only ps_capacity1.html with extension of base.html, everything is OK( got info from database, it works OK) but in bootstrap taps … -
local variable 'search_keyword' referenced before assignment
I have been working on a search form and it's giving me this error when i open the url or submit the form. I am watching a codemy django tutorial and the only thing that is different is that i have some code for pagination i don't know if that's what is affecting it. base.html <form method="post" action="{% url 'listing' %}" name="searchform"> {% csrf_token %} <div class="custom-form"> <label>Keywords </label> <input type="text" placeholder="Property Keywords" name="search_keyword" value=""/> <label >Categories</label> <select data-placeholder="Categories" name = "home_type" class="chosen-select on-radius no-search-select" > <option>All Categories</option> <option>Single-family</option> <option>Semi-detached</option> <option>Apartment</option> <option>Townhomes</option> <option>Multi-family</option> <option>Mobile/Manufactured</option> <option>Condo</option> </select> <label style="margin-top:10px;" >Price Range</label> <div class="price-rage-item fl-wrap"> <input type="text" class="price-range" data-min="10000" data-max="100000000000" name="price-range1" data-step="1" value="1" data-prefix="$₦"> </div> <button onclick="location.href='listing'" type="button" class="btn float-btn color-bg"><i class="fal fa-search"></i> Search</button> </div> </form> views.py def listing(request): if request.method == 'POST' and 'searchform' in request.POST : search_keyword = request.POST['search_keyword'] propertys = Property.objects.filter(name__icontains=search_keyword) p = Paginator(Property.objects.order_by('-listed_on'), 2) page = request.GET.get('page') propertys = p.get_page(page) nums = "p" * propertys.paginator.num_pages return render(request, 'listing.html',{'search_keyword':search_keyword,'nums':nums,'propertys':propertys}) -
Deploying a Django application to Heroku - No module named 'django_project.wsgi
I'm trying to deploy a django application but I keep getting this error: ModuleNotFoundError: No module named 'django_project.wsgi' In fact, here's the full log: 2022-05-13T14:52:06.436735+00:00 app[web.1]: Traceback (most recent call last): 2022-05-13T14:52:06.436735+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-05-13T14:52:06.436736+00:00 app[web.1]: worker.init_process() 2022-05-13T14:52:06.436736+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-05-13T14:52:06.436736+00:00 app[web.1]: self.load_wsgi() 2022-05-13T14:52:06.436737+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-05-13T14:52:06.436737+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-05-13T14:52:06.436738+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-05-13T14:52:06.436738+00:00 app[web.1]: self.callable = self.load() 2022-05-13T14:52:06.436738+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-05-13T14:52:06.436740+00:00 app[web.1]: return self.load_wsgiapp() 2022-05-13T14:52:06.436740+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-05-13T14:52:06.436740+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-05-13T14:52:06.436741+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-05-13T14:52:06.436741+00:00 app[web.1]: mod = importlib.import_module(module) 2022-05-13T14:52:06.436741+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2022-05-13T14:52:06.436742+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-05-13T14:52:06.436742+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-05-13T14:52:06.436742+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2022-05-13T14:52:06.436742+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2022-05-13T14:52:06.436742+00:00 app[web.1]: ModuleNotFoundError: No module named 'django_project.wsgi' 2022-05-13T14:52:06.436801+00:00 app[web.1]: [2022-05-13 14:52:06 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-05-13T14:52:06.442147+00:00 app[web.1]: [2022-05-13 14:52:06 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-05-13T14:52:06.541420+00:00 app[web.1]: [2022-05-13 14:52:06 +0000] [4] [INFO] Shutting …