Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dictionary only adds in the last key value pair in for loop
I have a for loop that goes through a list of cities and assigns them each a total_city_value. I am trying to get each unique total_city_value created during the for loop added to the dictionary however it seems to be only keeping the final total_city_value in the for loop when I print the dictionary. for broad_variable in broad_variable_list: # check if the current broad variable is equal to the first broad variable the user chose if broad_variable == broad_variable1: # if the city's specific variable is equal to the specific variable the user chose get the value of it based on it's ranking weight if City.objects.values_list(broad_variable, flat=True).filter(city=cities).first() == specific_variable1: city_variable1_value = 1 * weight_variable1 #print("city_variable1_value",city_variable1_value) # else assign a value of 0 else: city_variable1_value = 0 # check if the current broad variable is equal to the second broad variable the user chose if broad_variable == broad_variable2: # if the city's specific variable is equal to the specific variable the user chose get the value of it based on it's ranking weight if City.objects.values_list(broad_variable, flat=True).filter(city=cities).first() == specific_variable2: city_variable2_value = 1 * weight_variable2 # else assign a value of 0 else: city_variable2_value = 0 total_city_value = city_variable1_value + city_variable2_value city_value_dictionary[cities] = … -
How to run Django tests in Docker using GitHub Actions
I am building my first full CI/CD pipeline for a Django/React.js project. It uses 2 workflows: build.yml and deploy.yml. The build.yml first builds the images then pushes them to the GH Packages. Then it pulls the images in a new job and runs tests (though I think this is wrong as I think jobs run in parallel - haven't got to this part yet). Build.yml name: Build and Test on: push: branches: - development env: BACKEND_IMAGE: ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/backend NGINX_IMAGE: ghcr.io/$(echo $GITHUB_REPOSITORY | tr '[:upper:]' '[:lower:]')/nginx jobs: build: name: Build Docker Images runs-on: ubuntu-latest steps: - name: Checkout master uses: actions/checkout@v1 - name: Add environment variables to .env run: | echo DEBUG=0 >> .env echo SQL_ENGINE=django.db.backends.postgresql >> .env echo DATABASE=postgres >> .env echo SECRET_KEY=${{ secrets.SECRET_KEY }} >> .env echo SQL_DATABASE=${{ secrets.SQL_DATABASE }} >> .env echo SQL_USER=${{ secrets.SQL_USER }} >> .env echo SQL_PASSWORD=${{ secrets.SQL_PASSWORD }} >> .env echo SQL_HOST=${{ secrets.SQL_HOST }} >> .env echo SQL_PORT=${{ secrets.SQL_PORT }} >> .env - name: Set environment variables run: | echo "BACKEND_IMAGE=$(echo ${{env.BACKEND_IMAGE}} )" >> $GITHUB_ENV echo "NGINX_IMAGE=$(echo ${{env.NGINX_IMAGE}} )" >> $GITHUB_ENV - name: Log in to GitHub Packages run: echo ${PERSONAL_ACCESS_TOKEN} | docker login ghcr.io -u ${{ secrets.NAMESPACE }} --password-stdin env: … -
Django - How to annotate a single Django object
So Django has this cool feature where you can annotate a query set as in you can add attributes to each object in a query set. For example if I have a query set of users I can annotate it with number of followers which is another table with a foreign key reference to user. This can be done with the QuerySet.annotate() function. I was wondering if this is possible for a single Django object. I have a view function that gets user info, which given a unique user UUID I return the users info in the user table as well as the number of followers and followees. 1 way to do this is just query across all follower and followee table for the uuid and create a dictionary that gets returned or annotate a single object. Is it possible to do this? views.py @api_view(['GET']) def get_user_info(request, user_uuid): is_current_user = user_uuid == str(request.user.uuid) # Return all user info including # of followers and followees models.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) class FollowUser(AbstractSimpleModel): follower = models.ForeignKey( User, on_delete=models.CASCADE, related_name='follower_id') followee = models.ForeignKey( … -
Accessing foreign key attributes for arithmetics in django rest framework
I'm trying to calculate the length of a house relative to some adjacent neighborhoods, such that, house_size / (neighborhood[0].length + neighborhood[1].length...): class House(models.Model): house_id = models.CharField(max_length=256, primary_key=True) size = models.IntegerField() neighborhood = models.ManyToManyField('neighborhood', through='HouseNeighborhoodLink') class Neighborhood(models.Model): length = models.IntegerField() I created a table to assign several neighborhoods with a house. Also, houses can be assigned to several adjacent neighborhoods: class HouseNeighborhoodLink(models.Model): house_id = models.ForeignKey(House, on_delete=models.DO_NOTHING) neighborhood = models.ForeignKey(Neighborhood, on_delete=models.DO_NOTHING) Serializers: class LengthFromNeighborhoodSerializer(serializers.ModelSerializer): class Meta: model = Neighborhood fields = ['length'] class HouseCoverageOfNeighborhood(serializers.ModelSerializer): Neighborhood = LengthFromNeighborhoodSerializer(read_only=True) class Meta: model = HouseNeighborhoodLink fields = ['house_id', 'Neighborhood'] I'm stuck in the three dots (...), where I want to access the length attribute of all neighborhoods and then calculate the proportion to a house. I'm not sure how to access the length of each neighborhood from HouseNeighborhoodLink table: class HouseCoverageDetail(generics.ListAPIView): queryset = HouseNeighborhoodLink.objects.all() serializer_class = HouseCoverageOfNeighborhood def get_queryset(self): house_id = self.kwargs['house_id'] neighborhood = self.queryset.filter(house_id=house_id) ... return result -
"Unknown pytest.mark.django_db" when trying to run test for django-treebeard
I'm trying to run the following test from django-treebeard: In case you know what you are doing, there is a test that is disabled by default that can tell you the optimal default alphabet in your enviroment. To run the test you must enable the TREEBEARD_TEST_ALPHABET enviroment variable: $ TREEBEARD_TEST_ALPHABET=1 py.test -k test_alphabet I have Django and PostgreSQL setup via Docker: Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 ENV TREEBEARD_TEST_ALPHABET=1 ENV DATABASE_USER = "postgres" ENV DATABASE_PASSWORD = "postgres" ENV DATABASE_HOST = "db" ENV DATABASE_USER_POSTGRES = "postgres" ENV DATABASE_PORT_POSTGRES = 5432 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --dev --system COPY . /code/ docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Pipfile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "~=3.2" djangorestframework = "*" ulid2 = "*" psycopg2 = "*" django-lifecycle = "*" django-filter = "*" django-cors-headers = "*" djangorestframework-simplejwt = "*" django-allauth = "*" dj-rest-auth = "*" django-treebeard = "*" djangorestframework-recursive = "*" [dev-packages] black = "*" django-debug-toolbar = "*" drf-yasg = "*" coverage = … -
How do I reuse a ModelForm for a through model with an additional field?
I have a Model Example and corresponding ModelForm ExampleModelForm that I use in ModelFormset ExampleModelFormset = modelformset_factory(Example, form=ExampleModelForm) I have a many-to-many through Model with an additional property. class ExampleThrough(models.Model): batch = models.ForeignKey(Batch, on_delete=models.CASCADE) example = models.ForeignKey(Example, on_delete=models.CASCADE) property = models.FloatField() Is there a way to reuse the ExampleModelForm to create a ExampleThroughModelForm that I can also use in a ExampleThroughModelFormset? I want to have all of the same fields as the ExampleModelForm plus the one new property. I don't think I can inherit from the ExampleModelForm: class ExampleThroughModelForm(ExampleModelForm): class Meta: model = ExampleThrough fields = '__all__' because the documentation has this note: Normal Python name resolution rules apply. If you have multiple base classes that declare a Meta inner class, only the first one will be used. This means the child’s Meta, if it exists, otherwise the Meta of the first parent, etc. -
Desired Outcome: I want to dynamically create and render data from a One to Many Field to a template in Django
I have two models with One to Many relationship. The Models are Parent and Child respectively. I have managed to dynamically render data from the Parent Model, but now I want to be able to put a link to to each Parent Record, such that when clicked it will create a Child record and render out the child information to the respective parent. #Models class Parent(models.Model): surname = models.CharField(max_length=150, null=False, blank=False) first_name = models.CharField(max_length=150, null=False, blank=False) class Child(models.Model): parent = models.ForeignKey(Parent, null=True, blank=True, on_delete=SET_NULL) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) views.py def display(request, pk): parents = Parent.objects.get(id=pk) child = parents.child_set.all() context = {'parents':parents, 'child':child} return render(request, 'reg/info_page.html', context) I have tried to implement the reverse relation but when I try to display the child's information, it comes up blank. div class="col-md-4 col-sm-4 text-center"> <p class="text-purple">Child Name</p> <h1>{{child.first_name}}</h1> </div> -
Django - Error when changing from GET to POST
I have a react/django application that works fine when the request is a GET request. For example, in the React part I have the following sendRequestParameters(url) { axios({ url: url, method: 'get', headers: { 'X-CSRFToken': 'csrf_token', 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8', }, params:{ 'TECHNOLOGY': JSON.stringify(this.state.technologySelectedValue), // more parameters here, all in the same format }, paramsSerializer: function(params) { return qs.stringify(params, {arrayFormat: 'repeat'}) } }).then((response ) => { console.log(response.data); }).catch((error) => { console.log(error) }) } Then, in the backend, I get the parameters and return them (this function is called in another function where the returned parameters are used, that's why there is a return statement). def extractParameters(request): TECHNOLOGY = json.loads(request.GET.get('TECHNOLOGY')) # more parameters extracted here, same format return TECHNOLOGY etc. That all works fine. However, I need to change to POST requests, and when I make two small modifications to do this, I get an error. In the front end request with axios, I change the method: 'get' to method: 'post'. Then, in the backend, I change TECHNOLOGY = json.loads(request.GET.get('TECHNOLOGY')) to TECHNOLOGY = json.loads(request.POST.get('TECHNOLOGY')) This gives me the following error in the terminal TECHNOLOGY = json.loads(request.POST.get('TECHNOLOGY')) raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object … -
Insert bulk data into postgresql with Django
I'm using heroku and trying to create a project that uses postgresql. I have a model like this: class Customer(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLDE = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze'), (MEMBERSHIP_SILVER, 'Silver'), (MEMBERSHIP_GOLDE, 'Gold'), ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=14) birth_date = models.DateField(null=True, blank=True) membership = models.CharField(max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) I'll use a mock data like this: insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (1, 'Lissy', 'Rissen', 'lrissen0@bloglovin.com', '105-879-7972', '2000-11-07', 'G'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (2, 'Peterus', 'Caddens', 'pcaddens1@usda.gov', '471-936-4037', null, 'G'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (3, 'Debee', 'Ceschini', 'dceschini2@cyberchimps.com', '526-812-6447', null, 'B'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (4, 'Inessa', 'Blogg', 'iblogg3@mail.ru', '656-866-8989', '1985-10-21', 'S'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (5, 'Charline', 'Mayberry', 'cmayberry4@statcounter.com', '609-214-0294', '1999-09-20', 'B'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (6, 'Bunni', 'Furness', 'bfurness5@webmd.com', '926-176-0613', '2018-07-02', 'G'); insert into store_product (id, first_name, last_name, email, phone, birth_date, membreship) values (7, 'Juana', 'Double', 'jdouble6@mysql.com', '873-793-8148', '2015-03-04', 'G'); insert into store_product (id, first_name, last_name, email, … -
Getting the value of two rational variables inside a for loop and adding them outside the for loop
I have two for loops in my program. The first for loop goes through a list of cities and the second for loop goes through a list of broad variables (safety, affordability, transit, etc). Inside the second for loop I assign a value to each city's broad variable city_variable1_value = 1 * weight_variable1 and city_variable2_value = 1 * weight_variable2. Inside the first for loop I add both city variables to get a total value total_city_value = city_variable1_value + city_variable2_value however this value is consistently outputting as 0 instead of the desired outcome 0.57 Here are my print outputs for print("city_variable1_value",city_variable1_value) is 0.24 print("city_variable2_value",city_variable2_value) is 0.33 print("total_city_value",total_city_value) is 0 views.py def get_ranking(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = RankingForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required specific_variable1 = form.cleaned_data['specific_variable1'] specific_variable2 = form.cleaned_data['specific_variable2'] broad_variable1 = form.cleaned_data['broad_variable1'] broad_variable2 = form.cleaned_data['broad_variable2'] # loop through each city in the database for cities in City.objects.values_list('city', flat=True): print("cities",cities) # loop through each broad variable in the list at the top of this … -
how to auto scroll down when new messages added
I am working with django , I want to scroll down auto when new messages added 'sent or received', I can scroll down auto when I refrech the page because of this code line : $("#card-body").animate({ scrollTop: 20000000 }, "slow"); but when I send and I receive new messages the messages go down until I can't see them I have to scroll down manually this is the js code : <script> /* send message*/ document.getElementById('send-btn-id').onclick = function (e) { const msg = document.getElementById('message').value; chatSocket.send(JSON.stringify({ 'message': msg, 'user': me, 'friend': friendName })); document.getElementById('message').value = ""; }; const friendName = JSON.parse(document.getElementById('friend').textContent); const me = JSON.parse(document.getElementById('me').textContent); /* set friend profile name */ document.getElementById('friend-name').innerHTML = friendName['username']; /* start conversation */ document.querySelector('.start-conversation').innerHTML = 'Start conversation with <strong>'+friendName['username']+'</strong>'; /* connection request */ const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + friendName['username'] + '/' ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); var class_name = 'in'; var profile_image = '{{friend_obj.profile.image.url}}'; if(me['username'] == data.user['username']) { data.user['username'] = 'Me'; class_name = 'out'; profile_image = '{{request.user.profile.image.url}}'; } var chat_list = document.querySelector('#chat-list-id'); var chat = "<li class=\""+class_name+"\"><div class=\"chat-img\"><img alt=\"avatarchat\" src=\""+profile_image+"\"></div><div class=\"chat-body\"><div class=\"chat-message\"><h5>"+data.user['username']+"</h5><p>"+data.message+"</p></div></div></li>"; chat_list.innerHTML += chat; }; </script> -
Limit Django ModelForm ForeignKey choices depending on request.user
It is sometimes desirable to restrict the choices presented by the ForeignKey field of a ModelForm so that users don't see each others' content. However this can be tricky because models do not have access to request.user. Consider an app with two models: class Folder(models.Model): user = models.ForeignKey(get_user_model(), editable=False, on_delete=models.CASCADE) name = models.CharField(max_length=30) class Content(models.Model): folder = models.ForeignKey(Folder, on_delete=models.CASCADE) text = models.CharField(max_length=50) The idea is that users can create folders and content, but may only store content in folders that they themselves created. i.e.: Content.folder.user == request.user QUESTION: How can we use for example CreateView, so that when creating new content users are shown the choice of only their own folders? -
How to get item by hashed CharField in django
I have Device model that has a field named token that stores a pbkdf2_sha256 hashed string. from django.contrib.auth.hashers import make_password from django.models import Model, CharField class Device(Model): name = CharField(max_length=200) token = CharField(unique=True, max_length=128) def save(self,*args,**kwargs): self.token = make_password(self.token) super().save(*args,**kwargs) for example I have a Device object that it's token is hashed value of ABCD. now question is if I get ABCD from user as raw token, how i can find it's device from database? I tried this: I hashed the ABCD that I got from user with make_password, but the new hashed value wasn't as same as the old one that was in db. also I know that I can get device id from user and then check if user's entered token is same with check_password method. but I want only get token from user not device id and token. -
Django runserver memory leak?
Seemingly out of nowhere, whenever I called the url for my Django model, be it with ListView or DetailView, it would hang, and while doing so the memory would spike and I had to kill runserver. I have now tracked this issue down to subprocess._try_wait(). The simple solution seems to be to raise ChildProcessError. But this is source code, and I've always been told not to mess with source. So how am I supposed to fix this? With a decorator? That still has to go in the source, doesn’t it? Please advise. Also, I note that there is a comment in the source code about a python bug in the method immediately preceding _try_wait(), which is _internal_poll(). See http://bugs.python.org/issue15756 . However, that bug was reported and fixed all the way back in 2012, and it was thought to be identical to 1731717, reported all the way back in 2007 and fixed in Python 3.2. This project is my first on Python 3.9.9, so I am hoping this bug has not been re-introduced. Django is 3.2.9, os is Ubuntu 20.04. Also, all these comments and bug reports talk about “SIGCLD is set to be ignored.” But if that’s the better way … -
License key generation after purchase with django
Hi I was wondering how its possible with django to generate a license key once someone has made a purchase on my site, I'm still trying to learn the framework and understand how it works. I'm guessing it would be something to do with views.py as it would be a request but as I said i'm only just learning the basic fundamentals as of right now and I've done some research and I cant seem to find much. -
Cloudrun Django+Terraform / 404 error on app URL
I just followed this tutorial : https://github.com/GoogleCloudPlatform/serverless-expeditions/tree/main/cloud-run-django-terraform I've done : gcloud builds submit --config cloudbuild-migrate.yaml terraform apply -var project=$PROJECT_ID My database was created. Service was pushed online well and I've got a service_url. When I access it, it shows a 404 error. Even if try to access the /admin page, it just returns a 500 error with no explanation in the log journal (or I didn't find it). When I try to runserver on localhost with sql_cloud_proxy, Django work perfectly. It's just a Django basic project showing hello on homepage. I don't get it. Here's my settings.py file : import io import os from pathlib import Path import environ import google.auth from google.cloud import secretmanager BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env(DEBUG=(bool, False)) env_file = os.path.join(BASE_DIR, ".env") # Attempt to load the Project ID into the environment, safely failing on error. try: _, os.environ["GOOGLE_CLOUD_PROJECT"] = google.auth.default() except google.auth.exceptions.DefaultCredentialsError: pass if os.path.isfile(env_file): # Use a local secret file, if provided env.read_env(env_file) elif os.environ.get("GOOGLE_CLOUD_PROJECT", None): # Pull secrets from Secret Manager project_id = os.environ.get("GOOGLE_CLOUD_PROJECT") client = secretmanager.SecretManagerServiceClient() settings_name = os.environ.get("SETTINGS_NAME", "django_settings") name = f"projects/{project_id}/secrets/{settings_name}/versions/latest" payload = client.access_secret_version(name=name).payload.data.decode("UTF-8") env.read_env(io.StringIO(payload)) else: raise Exception("No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found.") SECRET_KEY = env("SECRET_KEY") # … -
What is the name of that HTTPS session recorder & playback tool that has an API? Alt. how would you automate an HTTPS website to do user functions?
I've successfully used the tool before. It has a local webpage UI that you goto in your browser that lists the https traffic that occured, and options to play it back. It also comes with a command line tool. I am thinking of a small word ending in "mt", but can't seem to get google to find it. If you can offer any other suggestions that would also be great. Also, would that be an acceptable way to automate an HTTPS session for a website? There's a website I have to automate for a job, and they provide no API to help do the things that users can do on the site, so I am automating from scratch. Thank you for any guidance. I am not allowed to use Selenium webdriver. The code will be hosted on a Django host and the frontend to the automation scripts will be a Django website. -
Tweepy Stream Stop/Start Programatically
I am trying to build a web application using Django to track tweets by hashtags. I am using Tweepy Asyncstreaming and it's working fine. I am new to async programming. I need help with how to stop the running stream and start a new stream when a new hashtag is added. Here is my code: import os from tweepy.asynchronous import AsyncStream import asyncio consumer_key = os.getenv('XXXXXXXXXXX') consumer_secret = os.getenv('XXXXXXXXXXX') access_token = os.getenv('XXXXXXXXXXX') access_token_secret = os.getenv('XXXXXXXXXXX') async def main(): stream = TweetStream(consumer_key, consumer_secret, access_token, access_token_secret) await stream.filter(follow=['web3', 'crypto']) class TweetStream(AsyncStream): async def on_connect(self): print('Stream connected') async def on_status(self, status): if status.in_reply_to_user_id == None and not(status.entities['user_mentions']): print(status.text) print(status.user.screen_name) async def on_error(self, status): print(status) if __name__ == '__main__': asyncio.run(main()) -
How to Search Tags in Wagtail
How do you search wagtail tags? This is my code for my search bar in my webapp: def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: search_results = Page.objects.live().search(search_query) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() Tags already have been set up. I tried using this code to make the tags in my model searchable but it didn't work: search_fields = Page.search_fields + [ index.SearchField('select_tags', partial_match=True), ] This is the webpage I looked at: https://docs.wagtail.io/en/stable/topics/search/indexing.html#wagtailsearch-indexing-fields -
How to prevent users from seeing all content in Django?
I have a website and I want to prevent visitors to seeing content unless they have permission. How can I restrict them? -
my website that based on Django and Nginx, can't be visited, instead, it downloads a blank file
I am getting this issue, only while requesting through the http protocol not ssl (https), I am using nginx for this server, all tags are correct(about content-types), nginx mime types settings are in standard status, and this is happening since a few days ago (earlier was fine)..! -
Django: get_absolute_url issue
I have been struggling through this issue for some time now... I have a model with two classes, and have a get_absolute_url function in both classes, but every time I try to use the function, I get the same response. models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Listing(models.Model): info = models.CharField(max_length = 200) def __str__(self): return self.info def get_absolute_url(self): return reverse('listing_detail', args = [str(self.id)]) class Application(models.Model): listing = models.ForeignKey( Listing, on_delete = models.CASCADE, related_name = 'applications', ) comment = models.TextField(max_length = 2500) def __str__(self): return self.comment def get_absolute_url(self): return reverse('applications', args = [str(self.id)]) urls.py from django.urls import path from .views import ListingListView, ListingDetailView, ListingApplicationView urlpatterns = [ path('', ListingListView.as_view(), name = 'listing_list'), path('<int:pk>/', ListingDetailView.as_view(), name = 'listing_detail'), path('<int:pk>/applications/', ListingApplicationView.as_view(), name = 'applications') ] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Listing, Application # Create your views here. class ListingListView(ListView): model = Listing template_name = 'listing/listing_list.html' context_object_name = 'listing_list' class ListingDetailView(DetailView): model = Listing template_name = 'listing/listing_detail.html' context_object_name = 'listing_detail' class ListingApplicationView(ListView): model = Application template_name = 'listing/applications.html' context_object_name = 'applications' templates <h2><a href="{{ listing.get_absolute_url }}">{{ listing.address1 }}</a></h2> <p><a href = "{{ applications.get_absolute_url … -
JWTAuth: KeyError
I want to inject JWTAuth into my chat project with websockets and I get this error when I go to the chat page, the chat itself does not work after I changed auth to my personalized JWT Can you please tell me what's wrong? Errors: HTTP GET /chat/lobby/ 200 [0.01, 127.0.0.1:60197] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:55592] Exception inside application: 'token' Traceback (most recent call last): File "C:\Users\ikoli\PycharmProjects\mychat\venv\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\ikoli\PycharmProjects\mychat\venv\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\ikoli\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\compatibility.py", line 34, in new_application instance = application(scope) File "C:\Users\ikoli\PycharmProjects\mychat\mychat\mychat\channelsmiddleware.py", line 25, in __call__ token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] KeyError: 'token' WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:55592] HTTP GET /chat/lobby/ 200 [0.00, 127.0.0.1:52491] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:63145] Exception inside application: 'token' Traceback (most recent call last): File "C:\Users\ikoli\PycharmProjects\mychat\venv\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\ikoli\PycharmProjects\mychat\venv\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\ikoli\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\compatibility.py", line 34, in new_application instance = application(scope) File "C:\Users\ikoli\PycharmProjects\mychat\mychat\mychat\channelsmiddleware.py", line 25, in __call__ token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] KeyError: 'token' WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:63145] consumers.py: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope["user"] self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name, self.user ) await self.accept() … -
Admin interface panel does not work when i assign user to a group in Django
When I click on button to assign a user to groups, page scroll to top of page and does not work This code is by inspect element on button: <li> <a title="Choose" href="#" id="id_groups_add_link" class="selector-add active">Choose</a> </li> I -
How do i write a jQuery input string so that it works with Django query string
Am working on a name search app but having a challenge getting it to work with Django query string, the challenge which i observed comes from my JavaScript input type with ${input} string when added to Django query string eg. "address/get-name/?search=${input}" doesn't return the query object or the payload data, instead it return an empty list, but when i make search through the browser it return all search query data eg "address/get-name/?search=smith", Now how do i get input through my scripts without having to use the java scripts query input type ${input} with django so let i get a query string like this "address/get-name/?search=james" ? Here is my script, Am a novice in JavaScript <script> new Autocomplete('#autocomplete',{ search : input => { console.log(input) const url = "/address/get-names/?search=${input}" return new Promise(resolve => { fetch(url) .then( (response) => response.json()) .then( data => { console.log(data.playload) resolve(data.playload) }) }) }, rennderResult : (result, props) =>{ console.log(props) let group = '' if (result.index % 3 == 0 ){ group = '<li class="group">Group</li>' } return '${group}<li ${props}><div class="wiki title">${result.name}</div></li>' } }) </script> my view.py def get_names(request): search = request.GET.get('search') payload = [] if search: objs = Names.objects.filter(name__startswith=search) for obj in objs: payload.append({ 'name' : obj.name }) …