Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle token in dajngo rest when user close the browser?
I'm new to the Django rest framework and I'm tyring token auth of Django rest but I have no idea how to handle token when user directly close the browser without logout, In such a case what will be the standard way? Also, I want to implement if a user is already logged in then redirect to the dashboard how to implement this? My views are as follow. class LoginTemplateClass(TemplateView): template_name = 'index.html' class LoginAPI(viewsets.ModelViewSet): serializer_class = LoginSerializer def post(self,request): try: serializer = self.serializer_class(data=request.data,context={'request': request}) if serializer.is_valid(): user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response(token.key,status = 200) return Response(serializer.errors,status = 400) except Exception as e: return Response({},status = 500) -
How to make post call if I have JSON in django
I am working on django project where I have JSON data for Post call request to trigger the post function. here's my view def jiranewsprint(request): default_node = list(Lookup.objects.values('Name').filter(Type = 'JENKINS_NODES', default_node = 'Default').values())[0].get('Name') print('default_node',default_node) jextract= request.body print(jextract) jextract = json.loads(jextract) jiraSprint = jextract["issue"]["fields"]["customfield_10200"] print('jiraSprint',jiraSprint) sandboxcall= { "id": 18, "robot": "Sandbox_Creation_Bot", "param": [ { "node": default_node, "Username": "hello", "Password": "hello@21", "WebsiteURL": "https//:google.com", "SandboxName": jiraSprint+'_sandbox', "Publishable": "Yes", "Description": "testing", "Tools": "Application Composer" } ] } print(sandboxcall) return HttpResponse(status=200) Need help that how make post call with the json request I have ? -
Have example or data about GAN Model web publishing?
i wonder GAN Model Web Publishing. to be more specific, I want to distribute the model I learned from Tensorflow to web. Afterwards, when the user gives the input image, it is desired to derive the output image through the model. so i search Github, google but I couldn't find a satisfactory result. Most example about image classification.. Just in case, have example or data about my question...? -
Passing variable values from one route to another in a token authenticated flask application
I have a flask token authenticated application implemented by flask jwt extended. Code import random import os from flask import Flask, jsonify, request, session from flask_cors import CORS from flask_jwt_extended import create_access_token from flask_jwt_extended import JWTManager import json app = Flask(__name__) app.config["JWT_SECRET_KEY"] = "some secret key" jwt = JWTManager(app) CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' secret_email = "xxxx@gmail.com" secret_pass = "password" @app.route("/") def home(): return jsonify({"msg":"Hello, World!"}) @app.route("/login", methods=["POST"]) def login(): email = request.json.get("email", None) password = request.json.get("password", None) if email != secret_email or password != secret_pass: return jsonify({"msg": "Bad username or password"}), 401 access_token = create_access_token(identity=email) return jsonify(access_token=access_token) @app.route("/configs") def configs(): a = random.randint(10,30) b = random.randint(1,5) summ = a+b return jsonify({"a":a,"b":b}) @app.route("/sumcollect") def sumcollect(): return jsonify({"sum is":summ}) if __name__ == "__main__": app.run(debug=False) The summ variable in route /configs needs to be accessed in route /sumcollect . I tried with session variables. But the token authentication and session variables are not working together. Is there any way to pass the variables in this case. Note: Just added django tag for this in case for them to look at to have a solution. -
Convert string to html in django
I have a Django project but I need to convert a string in Django to HTML I try BeautifulSoup but I fail. How can I convert it? Here is the code of views.py and HTML f= markdown2.markdown(util.get_entry(title)) return render(request, "encyclopedia/entry.html", { "fileContent": f }) HTML: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} {{ description | safe }} {{fileContent}} {% endblock %} -
I don't understand how to use the django 3rd party library djangorestframework-api-key
I'm trying to set up an authentication that requires a user to send an API key and secret in the header of a request before being able to create the data. I'm using djangorestframework-api-key found here: https://florimondmanca.github.io/djangorestframework-api-key/guide/. However, I'm struggling with how to use it properly. My models.py looks something like this: class UserTier(Base): key = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) api_key = models.CharField(max_length=1000, null=True, blank=True) tiers = models.ManyToManyField(Tier) start_date = models.DateTimeField() end_date = models.DateTimeField() def save(self, *args, **kwargs): api_key, self.api_key = APIKey.objects.create_key(name=self.user.key) super(UserTier, self).save(*args, **kwargs) Here is an example API endpoint view that I have made: class MLBTeams(ListAPIView): serializer_class = MLBTeamSerializer queryset = Team.objects.all() permission_classes = [HasAPIKey] I ran this to get the API Key and passed it through the header in postman: print(APIKey.objects.get_from_key('V9Js7vY7.s1xiK0pWtzbp1ZQA3e2NrT95qhUk1kRV')) #key stored in the UserTier object However, I'm still getting the following error: { "detail": "Authentication credentials were not provided." } Does anybody know how to use this library properly? -
Gitlab CD Django app on DigitalOcean droplet return permission denied for SSH
I'm trying to implement CD for my containerized(Docker, nginx) Django app using gitlab on DigitalOcean droplet. I have created a pair of SSH keys and add the public key to DigitalOcean platform. I can login to my droplet using that SSH key. Now, I have added the private key as the environment variable at gitlab as: $PRIVATE_KEY , so now when I run the deployment it return the permission denied error. Here's my : .gitlab-ci.yml: image: name: docker/compose:1.29.2 entrypoint: [""] services: - docker:dind stages: - build - deploy variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 before_script: - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - export WEB_IMAGE=$IMAGE/web:web - export NGINX_IMAGE=$IMAGE/nginx:nginx - apk add --no-cache openssh-client bash - chmod +x ./setup_env.sh - bash ./setup_env.sh - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY build: stage: build script: - docker pull $IMAGE/web:web || true - docker pull $IMAGE/nginx:nginx || true - docker-compose -f docker-compose.prod.yml build - docker push $IMAGE/web:web - docker push $IMAGE/nginx:nginx deploy: stage: deploy script: - mkdir -p ~/.ssh - echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_ed25519 - cat ~/.ssh/id_ed25519 - chmod 700 ~/.ssh/id_ed25519 - eval "$(ssh-agent -s)" - ssh-add ~/.ssh/id_ed25519 - ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts - chmod +x ./deploy.sh - scp -o StrictHostKeyChecking=no -r ./.env … -
css and js is not working in blog detail page wagtail
enter image description here CSS and JS is not working in blog detail page -
Django to heroku deployment issue
While attempting to deploy my django project, I am running into a strange error: There is a dependency that I didn't use, and uninstalled, that is still trying to load with requirements.txt during the build. I have since uninstalled all of the dependencies, removed it from requirements.txt, run makemigrations and migrate, and yet it still tries to load it, which crashes the deployment. PyGObject is the dependency. workflow: Procfile - web: gunicorn solarsystem.wsgi ran - pip3 freeze > requirements.txt the dependency is no longer showing after uninstalling it. however during build: Collecting PyGObject remote: Downloading PyGObject-3.42.0.tar.gz (716 kB) remote: Installing build dependencies: started remote: Installing build dependencies: finished with status 'done' remote: Getting requirements to build wheel: started remote: Getting requirements to build wheel: finished with status 'done' remote: Preparing wheel metadata: started remote: Preparing wheel metadata: finished with status 'done' ... ERROR: Failed building wheel for PyGObject ... ERROR: Could not build wheels for PyGObject which use PEP 517 and cannot be installed directly and here is my requirements.txt: asgiref==3.3.4 autopep8==1.5.7 boto3==1.17.108 botocore==1.20.108 click==8.0.1 cm-rgb==0.3.6 cycler==0.10.0 dj-database-url==0.5.0 Django==3.2.3 django-appconf==1.0.4 django-compressor==2.2 django-heroku==0.3.1 django-libsass==0.9 django-material==1.9.0 django-materializecss-form==1.1.17 django-on-heroku==1.1.2 django-sass-processor==1.0.1 gunicorn==20.1.0 hidapi==0.10.1 Jinja2==3.0.1 jmespath==0.10.0 kiwisolver==1.3.1 libsass==0.21.0 MarkupSafe==2.0.1 matplotlib==3.4.3 mpld3==0.5.5 numpy==1.21.2 Pillow==8.3.1 psutil==5.8.0 psycopg2==2.9.1 … -
How to add event for checked row
I'm using django and it's printing a table. Currently, using the latest jquery script, clicking the Transfer Selected Rows button moves the selected rows to the second table. But I'm managing a server and I want the second table to be saved and visible to users. Should I create another class model to store the second table? Alternatively, when moving to the second table for the checked row, I would like to change the select column to name column and add the user name currently logged in in bulk. Another method I thought of is to apply a different color to each checked row and save it to the server. That is, I have 2 teachers and I want to assign them to students. Help.. <table id="student-list" class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Sex</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.register_date|date:'Y-m-d' }}</td> <td>{{ student.age }}</td> <td>{{ student.sex }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Transfer Selected … -
Unable to save in different database in django?
I am trying to save data into different database but its not saving and not giving any errors. settings.py I have two database mypage and ringi. mypage is set to default. DATABASE_ROUTERS = ['app_kanri.router.myrouter'] DATABASE_APPS_MAPPING = { 'ringi':'ringi_db' } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mypage', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'ringi_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ringi', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } models.py class Approvallog(models.Model): # id = models.IntegerField(primary_key=True) cat_name = models.CharField(max_length=100,default=None,blank=True) cat_id = models.IntegerField(default=None,blank=True) cat_subid = models.IntegerField(default=None,blank=True) status = models.IntegerField(default=None,blank=True) user = models.CharField(max_length=100,default=None,blank=True) app_root = models.IntegerField(default=None,blank=True) app_step = models.IntegerField(default=None,blank=True) comment = models.TextField(default=None,blank=True) created = models.DateTimeField(default=None,blank=True) modified = models.DateTimeField(default=None,blank=True) class Meta: app_label = 'ringi' db_table = "approvallogs" router.py class myrouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'ringi': return 'ringi_db' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'ringi': return 'ringi_db' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'ringi' or \ obj2._meta.app_label == 'ringi': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'ringi': return db == 'ringi_db' return None This is how I am saving Appr_log = Approvallog() Appr_log.cat_name=str(data2['cat_name']) Appr_log.cat_id=data2['cat_id'] Appr_log.cat_subid=data2['cat_subid'] Appr_log.status=data2['status'] Appr_log.user=data2['user'] Appr_log.save(using="ringi_db") I tried to print(Appr_log.save(using="ringi_db")) and … -
I'm doing a get request with fetch in a django app, it works in development but not in production and cannot get the problem
The application is deployed on heroku. When I run the program on my machine it works fine, but in production I get different errors. In Google Chrome in the console I get the following error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 In Firefox the error in the console is as follows Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data I received the following report from Sentry: Exception gaierror: [Errno 11001] getaddrinfo failed File "urllib3\connection.py", line 169, in _new_conn conn = connection.create_connection( File "urllib3\util\connection.py", line 73, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "socket.py", line 953, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x00000177DC7693A0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed File "urllib3\connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "urllib3\connectionpool.py", line 382, in _make_request self._validate_conn(conn) File "urllib3\connectionpool.py", line 1010, in _validate_conn conn.connect() File "urllib3\connection.py", line 353, in connect conn = self._new_conn() File "urllib3\connection.py", line 181, in _new_conn raise NewConnectionError( MaxRetryError: HTTPSConnectionPool(host='www.wordreference.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000177DC7693A0>: Failed to establish a new connection: [Errno … -
How can i make a custom user model in django without using username field?
I am working on building a project and for this, i need to create a custom user model, since the one that Django comes with isn't suitable for my situation, so whenever i use the AbstractBaseUser, I am forced to use the username field, which i really don't need in my case. how can I create a custom user model without using the username field and thank you -
Upload file from Django app to IBM Cloud Object Storage
I'm trying to connect a django app to IBM COS and having trouble. I'm capturing user video and want to save the file to IBM COS and the user info to Postgres also hosted on IBM. I'm able to connect from both the terminal and my app to IBM COS and move files around, but am having trouble getting the default storage configured properly. I'm using django-storages, trying to adapt the AWS configurations for IBM but I must be missing something. This code will save the file to IBM COS, but makes no entries in the DB. The problem may be in the configuration? Also, I am not able to manually upload a file form the django admin panel - I get a similar traceback. Thanks in advance for any help. settings.py # IBM STORAGE CONFIG IBM_API_KEY_ID = 'IBM_API_KEY_ID' IAM_SERVICE_ID = 'IAM_SERVICE_ID' ENDPOINT = 'https://s3.us-east.cloud-object-storage.appdomain.cloud' IBM_AUTH_ENDPOINT = 'https://iam.bluemix.net/oidc/token' SERVICE_INSTANCE_ID = 'SERVICE_INSTANCE_ID' IBM_STORAGE_BUCKET_NAME = 'cloud-object-storage-3u-cos-standard-77w' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' models.py class Video(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) videofilename=models.CharField(max_length=500) videofile=models.FileField(upload_to="video/", null=True, verbose_name="") def __str__(self): return str(self.videofile) views.py class upload_to_ibm_auto(LoginRequiredMixin, CreateView): model = Video context_object_name = 'Videos' form_class = VideoForm template_name = 'app_video/upload_to_ibm_auto.html' success_url … -
How can I remove the None or set the good status for a celery task?
Hello when I launch a celery task I got that for instance : [2021-09-22 22:11:26,878: INFO/ForkPoolWorker-7] Task Todos.celery.launchalert[886eb5a6-66cf-4759-a208-7245aca9882b] succeeded in 26.386354280999512s: None If the task is ok or have errors I got None and succeeded ... How can I do to either remove that either show the right logs ? Thank you very much ! -
Django Migration Modify Inherited Default
I have a model class in Django Parent with a subclass Child. Parent has a boolean field foo which defaults to True that Child inherited. I'd like to migrate my Child class so that All new Child objects have a default of False for the foo field All existing Child objects have the foo field set to False How can I achieve this in Django? -
Can I extend my Django project with FastAPI without changing the django app?
I have developed a Django e-commerce platform and then realized that I need to use FastAPI with it in order for my website to accept payments from the square payment system. I have looked through their documentation about how to do it, and they use fast API. However, I have no experience using Fast API at all. Is there a way for me to set up this fast API functionality without changing my Django project (so that it runs "together" with my Django app)? Or maybe there is another way which you would recommend me to use? -
Django static file problem. Clicking on the files downloads
sorry for my bad english. My index.html file cannot find the files in the static folder. When I view the page source, I click on the css file and I get different errors from time to time. Sometimes I get 404 error when I click on css link. Sometimes when I click on the css file, it downloads the file. Settings.py: import os from pathlib import Path DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "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', ], }, }, ] AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'tr' TIME_ZONE = 'Europe/Istanbul' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Urls.py: from django.conf import settings from django.conf.urls import static from django.contrib import admin from django.urls import path from django.urls.conf import include from django.conf.urls.static import static urlpatterns = [ path('', include("home.urls"), name="anasayfa"), … -
Django is not populating correctly an specific form using a Queryset
I have created two models Leads and Deals, and I have coded some logic such that if you click a button the Lead becomes a Deal, so what I want it is that a new form is presented to the user but that form already contains the information from the Leads model. @login_required def close_lead(request): if request.method == 'POST': deal_form = DealForm(request.POST) if deal_form.is_valid(): deal_form.save() messages.success(request, 'You have successfully updated the status from open to Close') id = request.GET.get('project_id', '') obj = Leads.objects.get(project_id=id) obj.status = "Closed" obj.save(update_fields=['status']) return HttpResponseRedirect(reverse('dashboard')) else: messages.error(request, 'Error updating your Form') else: id = request.GET.get('project_id', '') obj = get_object_or_404(Leads, project_id=id) print(obj.expected_revenue) form = NewDealForm(request.POST or None, instance=obj) return render(request, "account/close_lead.html", {'form':form}) I have done some debug and printed to the console the queryset and the information is fine, so the queryset is no the problem, the problem is that the NewForm doesn't prepopulate the new values. models.py (only 2 models shown) class Leads(models.Model): CHOICES = ( ('Illumination Studies','Illumination Studies'), ('Training','Training'), ('Survey Design','Survey Design'), ('Software License','Software License') ) STATUS = (('Open','Open'), ('Closed','Closed'), ('Canceled', 'Canceled') ) project_id = models.BigAutoField(primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent") created_at = models.DateTimeField(auto_now_add=True) point_of_contact = models.ForeignKey(Client, on_delete=models.CASCADE) expected_revenue = MoneyField(max_digits=14, … -
Django Combine Many Unrelated Models on Related Foreign Key
I have 3 models T, E, Q such that: class E(Model): name_e = CharField() class T(Model): name_t = CharField() e = ForeignKey(E) class Q(Model): name_q = CharField() e = ForeignKey(E) I also have Serializers for each: class ESerializer(ModelSerializer): class Meta: model = E fields = '__all__' class TSerializer(ModelSerializer): e = ESerializer() class Meta: model = E fields = '__all__' class QSerializer(ModelSerializer): e = ESerializer() class Meta: model = E fields = '__all__' For one E row there can be many T and Q rows. I can make a query such that t = T.objects.filter(e__id=1).all() serialized_t = TSerializer(t, many=True).data And the output of serialized_t will look something like: [ {id:7, name_t:'test_1', e:{id:1, name_e:'ename_1'}}, {id:9, name_t:'test_2', e:{id:1, name_e:'ename_1'}} ] My question is how could I combine it so that I can include Q in the query above to create an output for the T query which would also include all Q's where e_id=1 and hence it would look something like this: [ {id:7, name_t:'test_1', e:{id:1, name_e:'ename_1'}, q:[{id:4, name_q:'qname_1'}, {id:5, name_q:'qname_2'}]}, {id:9, name_t:'test_2', e:{id:1, name_e:'ename_1'}, q:[{id:4, name_q:'qname_1'}, {id:5, name_q:'qname_2'}]} ] I don't mind if this can be done in-query itself, or if it involves some appending to the SerializedT object, as long as … -
How do I use queryset.upgrade in a Django Admin action?
I have a Django Admin action which updates values (including foreignkeys) in a model. The code is: def staff_reset(self, request, queryset): updated=queryset.update(regstatus='registered', medicalform__medform_status='required', staffmonitoringform__monitoring_status = 'required', staffreleaseform__release_status ='required', staffethics__ethics_status = 'required', staffethics__i_agree=False) self.message_user(request, ngettext( '%d staff registration was successfully reset.', '%d staff registrations were successfully reset.', updated, ) % updated, messages.SUCCESS) staff_reset.short_description="Reset Staff Registrations" But I get an error message saying "Order has no field named 'medicalform__medform_status'". Any ideas on if I can use the queryset.update() with foreignkeys? Thanks in advance. -
How read files with load_workbook in heroku
My application is reading a file from my computer and this works fine in localhost mode. But in heroku I need to find and read this file, but it is not working: def carregaGeneroEspecie(self): wb = load_workbook(filename='/pages/setup/2021-02-12 All-DungBeetle-species_FVZ-Collection.xlsx') sheet2 = wb['Sheet1'] return sheet2 Is it possible to read xlsx files in heroku? How to find it? -
Issues with deployment on heroku from Django
I am needing help with deploying my Django app to heroku. My Django project works locally, but when I deploy to Heroku, the app crashes and cant load the index/home page. I'm not quite sure what the issue is with the GET request. here are the heroku logs --tail: 2021-09-22T20:25:16.636085+00:00 heroku[web.1]: Starting process with command `gunicorn solarsystem.wsgi` 2021-09-22T20:25:17.678063+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-09-22T20:25:17.678545+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [4] [INFO] Listening at: http://0.0.0.0:34748 (4) 2021-09-22T20:25:17.678598+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [4] [INFO] Using worker: sync 2021-09-22T20:25:17.681856+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [7] [INFO] Booting worker with pid: 7 2021-09-22T20:25:17.685446+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [7] [ERROR] Exception in worker process 2021-09-22T20:25:17.685447+00:00 app[web.1]: Traceback (most recent call last): 2021-09-22T20:25:17.685455+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-09-22T20:25:17.685455+00:00 app[web.1]: worker.init_process() 2021-09-22T20:25:17.685456+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-09-22T20:25:17.685456+00:00 app[web.1]: self.load_wsgi() 2021-09-22T20:25:17.685456+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-09-22T20:25:17.685457+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-09-22T20:25:17.685457+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-09-22T20:25:17.685458+00:00 app[web.1]: self.callable = self.load() 2021-09-22T20:25:17.685458+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-09-22T20:25:17.685458+00:00 app[web.1]: return self.load_wsgiapp() 2021-09-22T20:25:17.685458+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-09-22T20:25:17.685459+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-09-22T20:25:17.685459+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2021-09-22T20:25:17.685460+00:00 app[web.1]: … -
How to redirect to object returned by Ajax autocomplete in django?
I'm fetching objects from the database by using Ajax autocomplete on a common search input field. I would now like to make the rendered results clickable and redirect to the page of the object. // jQuery autocomplete search $(function () { $('#header-search-bar').autocomplete({ // data to be passed from backend source: '/autocomplete/', // length of search string minLength: 3, // redirect to pollers select: function(event, ui) { location.href="poller/" + ui.item.poller_id; } }) }) // Django view / backend query to database def autocomplete(request): if 'term' in request.GET: qs = Poller.objects.filter(poller_text__icontains=request.GET.get('term')) pollers = list() for poller in qs: pollers.append(poller.poller) return JsonResponse(pollers, safe=False) else: pass // Model class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) poller_text =models.CharField(min_length=250) // Redirect url to single Poller path('poller/<uuid:poller_id>/', render_single_poller, name='single_poller'), So the desired url for a redirect would be poller/poller_id/ The above jQuery approach renders the poller_text of each object but doesn't redirect to it. So how can I additionally "build" the required url and redirect to it as I don't know how to append more to the list than poller_text. Right now it returns http://127.0.0.1:8000/pollboard/poller/undefined -
How do I use a related name field in a Q object
I am building a search screen, and one of the query choices is to search by "string". So I am trying to get all instances of a string in a primary model AND any instances of the same string in a related model - but - I only want the related instances that exist with the string. For example - one could search for the word "Tiger" in the Program title field, library field, remarks field and also in the Segment Author field, title field, library field etc... So that being said - here's the models. class Program(models.Model): air_date = models.DateField(default="0000/00/00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) title = models.CharField(max_length=190) library = models.CharField(max_length=190, blank=True) remarks = models.TextField(null=True,blank=True) class Segment(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', ) title = models.CharField(max_length=190, blank=True) author = models.CharField(max_length=64,null=True,blank=True) voice = models.CharField(max_length=64,null=True,blank=True) library = models.CharField(max_length=190) summary = models.TextField() My Q object for Program looks like this... q_words = [] q_words = query.split() query_prog_title_array = reduce(or_,[Q(title__icontains=w) for w in q_words]) query_prog_library_array = reduce(or_,[Q(library__icontains=w) for w in q_words]) query_prog_remarks_array = reduce(or_,[Q(remarks__icontains=w) for w in q_words]) program_results = Program.objects.filter( query_prog_title_array | query_prog_library_array | query_prog_remarks_array).order_by('id').distinct() My Q object for Segment looks like this... q_words = [] q_words = query.split() query_title_array = …