Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 }) … -
NameError at /login/ name 'user' is not defined line 26
Django Login, for some reason it doesn't work. Please help me I don't have much to explain this is my views.py. Whenever I login it sends the error, I'm making a login/logout/signup system. Below is part of the with the error in it. (Line 26 is the main error) Also this is part of Dennis Ivanov's course for Django but I can't seem to solve the error. from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from django.contrib import messages from .models import Profile from django.contrib.auth.models import User from .forms import CustomUserCreationForm, ProfileForm def loginUser(request): if request.user.is_authenticated: return redirect('profiles') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] try: user = User.objects.get(username=username) except: messages.error(request, "Username does not exist") user = authenticate(request, username=user, password=password) if user is not None: login(request, user) return redirect('profiles') else: messages.error(request, "Username OR Password is incorrect") return render(request, 'users/login_register.html') def logoutUser(request): logout(request) messages.info(request, "User was logged out") return redirect('login') -
Best way to trigger ML model in Django
Hello experienced Django guys, I'm developing my first app in Django with ML model for recommending books. I was wondering what is the most appropriate way to activate the python script clicking the button and taking the value from drop menu. To make it less confusing here is some code example: <!DOCTYPE html> <head> <title>Books</title> <body> <h1>Welcome to books recommender page!</h1> <br> <select> <option disabled = "True" selected>Select your favourite book!</option> {% for books in books %} <option>{{book.name}}</option> {% endfor%} </select> <button>Calculate my recommendations</button> </body> </head> Basically, I've connected Djagno app with Postgre DB with books, created this simple drop menu which shows all data in column. Now I want to pass the selected value to my python ML model (which is executing the function like this): try: print(get_recommendations(selected_book, n=6)) except: print("No book at stock.") Any suggestion how should I pass the drop menu value and trigger the script by clicking the button? -
MultilingualQuerySet always returns empty list
I have a website with support for 2 languages but I have a problem with switching url's. So when user clicks link that leads to some category I get list index out of range my model class Category(models.Model): category = models.CharField(max_length=20,unique=True) def __str__(self): return self.category translations.py for my model class CategoryTranslationOptions(TranslationOptions): fields = ('category',) translator.register(Category, CategoryTranslationOptions) my code view that is responsible for getting product with said category categoryList = Category.objects.all() categoryName = categoryList.filter(Q(category_pl=categorySlug) | Q(category_en=categorySlug)) productsInfo = Product.objects.filter(category=categoryName[0]) What I'm doing in categoryName is looking for name in two languages in case if user switches language mid browsing. Then I get the first value of it because it's a list but the list is empty. update when I printed out categoryList = Category.objects.all().values() I didn't saw any translation-related fields but i can see them in admin panel so it is the case of not getting correct query from database -
Wher to look for custom teplate tag in django
I'm trying to understand how netbox application is working (https://github.com/netbox-community/netbox). In a template "sidenav.html" it uses a custom tag "nav" this way: {% load nav %} {% nav %} Can you tell me what's behind that and where or how can I find it? -
List view and a dynamic List view in Django
I am brand new to Python & Django programming. I would like to display a List view category and a dynamic List view on the same Web page which will display a list of subcategories that belong to the selected category. -
How can I make a decorator in models.py?
I have a football Team class in my django Model. I made 3 methods of win, draw and lose where the self.Points_of_the_season will be modified accordingly ( +3 for win, +1 for draw and +0 for lose). But When I wrote those methods, I have to change the self.Match_Played with each call of the 3 methods. How can I make a decorator called @play_match which will add 1 to the concerned field? This is the code of models.py: class Team(models.Model): Team_name = models.CharField(max_length=255) Foundation_year = models.IntegerField() Points_of_season = models.IntegerField(default=0) Match_Played = models.IntegerField(default=0) League = models.ForeignKey(League, on_delete=models.CASCADE) def __str__(self): return f"{self.Team_name}-{self.Foundation_year}" @play_match def win(self): self.Points_of_season += 3 @play_match def draw(self): self.Points_of_season += 1 @play_match def lose(self): pass -
TF400898: An Internal Error Occurred. Activity Id: 1fc05eca-fed8-4065-ae1a-fc8f2741c0ea
i’m trying to push files into git repo via azure API but getting activity_id error. I followed their documentation and trying to add simple file in my repo. Here is my code: import requests, base64 pat_token = "xxxx-xxxxx-xxxx" b64Val = base64.b64encode(pat_token.encode()).decode() payload = { "refUpdates": [ { "name": "refs/heads/main", "oldObjectId": "505aae1f15ae153b7fc53e8bdb79ac997caa99e6" } ], "commits": [ { "comment": "Added task markdown file.", "changes": [ { "changeType": "add", "item": { "path": "TimeStamps.txt" }, "newContent": { "content": "# Tasks\n\n* Item 1\n* Item 2", "contentType": "rawtext" } } ] } ] } headers = { 'Authorization': 'Basic %s' % b64Val, 'Content-Type': 'application/json', } params = ( ('api-version', '6.0'), ) response = requests.post('https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repo}/pushes', headers=headers, data=payload, params=params) Anyone knows how to solve this issue? I have also added this issue on their developer community -
Why is current admin not shown in django app?
I created a mock user profile in Django admin in the admin/auth/user view and assigned the user with all permissions (active, staff status, superuser status). In admin/<app_name>/user I gave the user all authorization permissions. In the Django admin panel, when I hit view site and enter the home view of the django application, the current user is different from the one that was visiting the admin page. Why is the current user different from the admin user? -
Defining view function for displaying postgres data in django
I created the wines database in postgresql (containing ID, names etc), and inserted around 300 observations. I would like to display names of every wine in drop menu with django. The urls.py are properly setted up. App name inside the project is: jacques. What have I done so far: models.py from django.db import connection from django.db import models class ListWines(models.Model): name = models.CharField(max_length=200) views.py from django.shortcuts import render from jacques.models import ListWines def showallwines(request): wines = ListWines.objects return render(request, 'main.html', { 'name':wines } ) main.html <!DOCTYPE html> <head> <body> <select> <option disabled = "True" selected>Select your favourite wine!</option> {% for wines in showallwines %} <option>{{wines.name}}</option> {% endfor %} </select> </body> </head> The postgres database is named jacques (column containing data that I want to display is name) is connected with app by setings.py, however it doesn't show names. How should I redefine my functions in order to see display in main.html drop menu?