Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
passing dynamic variable from parent template to child template in django
I have a template songs.html that includes a child template addToPlaylist.html. I need the title of song that is to be added to the playlist dynamically. Here is the code for songs.html which includes addToPlaylist.html. {% for song in songs %} <div class="col-16 col-sm-4 col-md-3 col-lg-2 single-album-item"> <div class="single-album"> <img src="{{MEDIA_URL}}{{song.image.url}}" alt=""> <div class="album-info"> <a href="{% url 'playSong' 'song' song.tittle %} "> <h5>{{song.tittle}}</h5> </a> <p>{{song.album}}</p> {% include "songs/addToPlaylist.html" with song_to_add=song.tittle %} <a data-toggle="modal" href="#addToPlaylist" style="color: dimgrey; font-size: small;">Add to Playlist</a> </div> </div> </div> {% endfor %} and this is the code for addToPlaylist.html <div class="form-group" style="width: 100%;"> <ul class="list-group list-group-flush" style="width: 100%;"> {% for playlist in playlists %} <li class="list-group-item"><a href="{% url 'addToPlaylist' playlist.name song_to_add %}">{{playlist.name}}</a></li> {% endfor %} </ul> </div> but assigning dynamic value to song_to_add does not work. The variable does not pass down to child template. Help regarding this will be highly appreciated.Thank you! Also I tried this solutions Assign variables to child template in {% include %} tag Django -
How to remove BOM header from InMemoryUploadedFile
Let's say I have sent CSV with BOM header in an API request and parse that file into pd.read_csv({file_with_bom_header}). As a result, my dataframe has incorrect column and break. Do you have a method to remove BOM header in InMemoryUploadedFile type? -
Django - Division of two specific fields in queryset
I am trying to get the lead conversion rate, by dividing the two fields in a queryset (lead_count and client_count) Here is the query qs = CustomerInformation.objects.filter(salesDepartment=department).filter(created_date__range=(start,end)) qs = qs.annotate(date=TruncYear('created_date')).values('date').annotate(lead_count=Count('status',filter=Q(status="lead")), client_count=Count('status',filter=Q(status="client"))) Is there any way to divide the field 'client_count' by the field 'lead_count' to obtain conversion rate? All help is appreciated, thanks! -
Not able to authenticate user in django
i tried everything but i cant authenticate user it never logs me in always gives false like its not able to read the table user = User.objects.filter(username = username , password = password) this works perfectly for login but authentication is important for professional work. i am using mysql database and i am passing the data through ajax request and i am getting the data to the function without any problem. please help.. models.py from django.db import models class user(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length=100) fullname = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone = models.CharField(max_length=50) password = models.CharField(max_length=100) ipaddress = models.CharField(max_length=200) class Meta: app_label = 'Play' db_table = 'user' Views.py from django.shortcuts import render from django.contrib.auth import authenticate from django.contrib.auth import authenticate, login, logout from Accounts.EmailAuthentication import EmailBackend from Play.models import user from django.contrib.auth.models import User from django.shortcuts import redirect from django.shortcuts import HttpResponse from django.contrib.auth.hashers import make_password def JoinRequest(request): if request.method == 'POST': fullname = request.POST['fullname'] email = request.POST['email'] username = request.POST['username'] phone = request.POST['phone'] password = request.POST['password'] cpassword = request.POST['cpassword'] #encpass = make_password(password) def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip if password != cpassword: return HttpResponse('Password Not Matching To … -
How to do dynamic dispatch in Django REST Framework without an extra request?
I've got a bunch of existing API endpoints with different URLs and parameters. I'd like to enable asynchronous execution of some of them by adding a general-purpose /tasks(?P<path>.+) endpoint which calls the path endpoint asynchronously, returning a Celery task ID for the client to check the status of the task at their leisure. So far it's very similar to another question, but I was hoping there would be an existing pattern to resolve and call the relevant view without sending another HTTP request. Even though it would be fast enough to send a request, it would be harder to debug. It seems this might be possible at the router registry, URL pattern or view level, basically stripping off the URL prefix and then using the built-in URL resolver to figure out what to call with a slightly modified request object. -
Django, call the same view function with and without parameter
I want to pass the image ID to the same view function and pass the Image to the template for display. In my analysis app urls.py I have used path('', views.image_analysis, name='home'), path('<int:id>/', views.image_analysis, name='image_display'), The view function is What should I do there to get the id in the function. If I do like def image_analysis(request, id) its giving error. def image_analysis(request): if request.method == 'GET': post_id = Image_upload.objects.get(id=id) all_images = Image_upload.objects.filter(user=request.user) return render(request, 'analysis/home.html', {'images': all_images} ) In the home.html template file. {% block content %} <div class="row"> <div class="col-sm-4"> <h2>Images</h2> <ul class="list-group"> {% for image in images %} <li class="list-group-item"><a href="{% url 'analysis:image_display' image.id %}">{{image.image_name}} -</a> {{image.status}}</li> {% endfor %} </ul> </div> <div class="col-sm-8"> Single Image will come here.</div> </div> The template HTML file is having 2 blocks the left one is with all the images from the user on clicking I want to display the image in the same place. Can you please help me. -
How to cache Django Rest Framework action decorator?
Error 10061 connecting to localhost:6379. No connection could be made because the target machine actively refused it. @action(detail=False,methods=['GET',],url_path='demoList') @method_decorator(cache_page(60 * 60 * 2)) @method_decorator(vary_on_cookie) def demo_method(self,request): pass -
filter on distance by using pointfield
I want to set the filter on distance by using the point field i have model shop class Shop(models.Model): distance = models.PositiveIntegerField(null=True) Shop_location = models.PointField(null=True) the shop can define a distance from its location under which its id show to another user. when the user shares its location and the user able to see the shop which satisfies the condition. the condition is that the distance calculated between the user and shop less than or equal to the distance given by the shop -
How do you manage gulp dist folder in Django static production deployment?
I would be interested how people implemented gulp dist folder for their production environment. Do you gitignore the dist folder and rerun the gulp in production? Do you then run Node and Django in the production environment? Do you just copy the result dist folder to the production during deployment ? Or do you run 2 codebases for the static files? I am considering what is the best way to go about it as I am not sure whether to install node jsut to deploy the static files. -
Calking a python script in docker container from another docker container holding django app
I am completely new to containers and docker. I build a simple django app for handling api service. Now there are two main algorithm running which provide the results. Right now the algorithms resides in the single container which is a django app. Now with the view to ease the scaling, upgrade I am thinking to separate the two algo in a two different containers. So three containers two for algo and one for handling django rest service. First of all i want to understand if my approach is right. Now how the communication will take place between the container. The algo is just pure python script. At present i just call the function and the result is passed as api response. Do I need to wrap my algo too in an api. I dont want to this actually since i want a single point to serve all api request which is the django app. So how I would call my python scripts running on a container from another container holding django app. -
Cannot run server in virtualenv on Gitbash "Couldn't import Django. Are you sure it's installed and
I am trying to run the django server locally on my gitbash. I started with the following command lines: virtualenv env pip install -r requirements.txt pip install django django-admin --version 3.0.7 pip --version 19.2.3 python --version 2.7.6 Variable PATH: C:\Users\circulating\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\circulating\AppData\Local\Programs\Python\Python37\;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Python27;C:\Users\circulating\AppData\Local\atom\bin;C:\Users\circulating\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Users\circulating\AppData\Roaming\npm;C:\Program Files\heroku\bin;C:\Program Files\nodejs;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem Error $ python manage.py runserver 0:8000 Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 13, in main "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Based off the error I need to: install Django(which is since i checked the version) Add to PYTHONPATH environment variable(not sure if or how to do this) Activate a virtual environment(activated in beginning) I am not sure if the problem is with my gitbash running on python2.7 as oppose to 3.7. The Django docs say Django(3.0) -> Python(3.6, 3.7, 3.8). However, I have both python 2.7 and 3.7 installed and in my PATH variable -
How do I do nested loops in Django?
I'm trying to output to a Django template one row that has four DIVs: I need to have two nested For Loops so that each time the fourth DIV is outputted, it will create a new row. In Java, it would be like this: for(int i = 0; i < object_list.length; i++){ <div class="row"> for(int j = 0; j < 4; j++){ <div class="col-md-3"> } } The code I'm using in the template is: {% for object in object_list %} {% with object|search as search_results %} {% if search_results == 'Post' %} [need to fill in appropriate HTML] {% endif %} {% endwith %} {% endfor %} How can I accomplish this? -
Django 3.0. Is there a way to update let say multiple users in a single page with a form?
What I'd like to do is that I want to show users and want to update them in a single page. The page looks like below user 1 user-name: <input> user-age: <input> user-gender: <input> user-birthday: <input> user 2 user-name: <input> user-age: <input> user-gender: <input> user-birthday: <input> <submit button> -
Get the current refresh token in backend in Django simple-jwt token authentication
I would like to received the refresh token in backend side to blacklist the token. I am getting the access token in request.header as user pass it in order to call the API, is there any way to get the refresh token while user is not passing in header. -
Django Render HTML via AJAX - Missing Context Variable Data
In my Django web app, I'm trying to dynamically update only a certain section of my page via AJAX, but doing so by returning/replacing HTML in a child template ({% include 'keywords.html' %}). I understand that I can (and maybe should) return a JsonResponse (and I have done so successfully), but I'd like to try and get the below implementation working (as others seem to have). The view successfully returns the HTML to the AJAX response, but lacking the data contained in the keywords context variable. templates/index.html ... <div id="keywords"> {% include 'keywords.html' %} </div> ... templates/keywords.html <div id="keywords"> {% if keywords %} {% for keyword in keywords %} <p>{{keyword.word}}</p> {% endfor %} {% endif %} </div> views.py def add_keyword(request): if request.method == 'POST': form = KeywordForm(request.POST) if form.is_valid(): ... keywords = Keywords.objects.values()... print(keywords) # this works, contains a queryset with data context = { keywords: keywords, } return render(request, 'keywords.html', context)) index.js // i've also tried jquery .load() $.ajax({ url: data.url, type: "POST", data: { keyword: keyword, csrfmiddlewaretoken: data.csrf_token }, success: function(data) { $("#keywords").html(data); } }); AJAX Response data: <div id="keywords"> </div> What might I be missing, or doing wrong? -
Django-registration-redux with postgresql
Does django-registration-redux work with postgresql? It's working fine with sqlite3, but throwing errors with postges. Have followed the documentation thoroughly. When I tried to migrate the error appears. -
Function field in model django
I have a model with a json field: from django.contrib.postgres.fields import JSONField data = JSONField(default=dict) I want each item in the model table to have its own way to interact with the json data field. For example: item 1: prints each element in the json item 2: print each element that is a list in the json item 3: print each element with a key that starts with "j" Thus, each item would need to store some data about how to do what is listed above. How could I achieve this in django with a postgres db? Thanks!! -
Implementing typeahead search with Django and React
I have a web app using Django for the backend and React for the frontend. I want to have a search option where the user can select what university they attend, and I already have a University table in my database. When the user types something in the search bar, it should bring up the matching entries from the University table (ex: user types in "S" and "Stanford" and "Swarthmore" show up). Are there any guides/tutorials that will help me with this? Is the best way for the frontend to request all colleges from the API endpoint in the beginning, then when the user types anything, it will get the relevant results from the data returned by the API endpoint? -
drf-yasg Customize SwaggerUIRenderer
I'd like to customize the style (font, colors, logo, etc) of drf_yasg generated docs. I see that I can extend drf_yasg/swagger-ui.html with the blocks extra_head, extra_styles, extra_body, extra_scripts, and can even overwrite the other blocks if I need to. What I am not clear on is how I point to my template that extends swagger-ui.html. I started with class MyCustomSwaggerUIRenderer(SwaggerUIRenderer): template = 'api/custom-swagger-ui.html' I want to replace SwaggerUIRenderer with MyCustomSwaggerUIRenderer in get_schema_view but do not understand how/where to do it without explicitly trying to enumerate all the other Renderers required too in some subclass of rest_framework.views.APIView and that seems convoluted. Pointers to docs or examples are appreciated. I've already read https://drf-yasg.readthedocs.io/ without success. -
What is the best way to import postgreDB into Django? [duplicate]
I'm developing Django web apps, and I already have a database created by PostgreSQL. Since dumped sql file can not directly import into Django, what is the best way to import? -
How to call the function in the class model when the field changes?
in this class when i add post I want to call category_change When the category field changes... how can i do that!? class Post(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey('Category', on_delete=models.CASCADE,null=True,blank=True,editable=False) image = models.ImageField(default='default.jpg', null=True, blank=True) series = models.ForeignKey('Series', on_delete=models.CASCADE,null=True,blank=True,editable=False) tags = models.ManyToManyField('FilmTags', related_name='post') content = models.TextField() watch = models.TextField(null=True, default='') download_url = models.CharField(max_length=300, null=True, default="#") created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) publish = models.BooleanField(default=True) views = models.IntegerField(default=0) def category_change(self): if category.title == "series": self.image.editable = True self.series.editable = True self.image = self.series.image else: self.image.editable = True -
how to convert large csv to json in action django-admin with celery?
I am trying to convert large csv in django-admin to be converted to json, through a django action that uses celery in the background. So that the user does not have to wait to finish for use the system. I have some errors, could your help? models.py class DataExtraction(models.Model): dataset = JSONField(blank=True, null=True) def __str__(self): return str(self.pk)class Extraction(models.Model): class Extraction(models.Model): name = models.CharField(max_length=100, blank=False, default=None) lawsuits = models.FileField(blank=True, null=False) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Extraction, DataExtraction from web.core.tasks import convert_data import csv def spider(modeladmin, request, queryset): for extraction in queryset: csv_file_path = extraction.lawsuits.path convert_data(csv_file_path).delay() spider.short_description = "Apply Spider" class ExtractionAdmin(admin.ModelAdmin): list_display = ['name'] actions = [spider] admin.site.register(Extraction, ExtractionAdmin) admin.site.register(DataExtraction) tasks.py: from celery import shared_task from web.celery import app from web.core.models import Tasks, DataExtraction, Extraction import csv def read_data_csv(path): with open(path) as csv_file: reader = csv.DictReader(csv_file, delimiter=',') csv_data = [line for line in reader] return csv_data @shared_task() def convert_data(path): dataset = read_data_csv(path) aux = [] for data in dataset: obj = DataExtraction(dataset=data) aux.append(obj) DataExtraction.objects.bulk_create(aux) print('finished!') Errors: (1) celery_1 | File "/code/web/core/tasks.py", line 17, in name celery_1 | def convert_data(path): celery_1 | AttributeError: 'FileDescriptor' object has no attribute 'path' (2) web_1 | File "/code/web/core/admin.py", line … -
Django-admin custom command don't store cache value
I've an unexpected behavior while using django command. I'm using the standard Django cache system. My settings : CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', 'TIMEOUT': 0, } } This is my command code : #coding: utf-8 import os import sys import time from django.core.management.base import BaseCommand from django.core.cache import cache class Command(BaseCommand): def handle(self, *args, **options): print(cache.get("mykey")) print(cache.set("mykey", "TEST", 300)) When I run it twice within the same minute I get the following output : (venv_crypto_bot) macbook-pro:project dauzon$ python manage.py generate_data None None (venv_crypto_bot) macbook-pro:project dauzon$ python manage.py generate_data None None I'm on the dev server. Clearly, Django don't store value in cache when I using a command. I don't know if it's due to I run the development server. Cache runs correctly when I visiting the webpages of my dev server. There are no details about the disabled cache (on command) in the Django documentation. How can I store cache value within a Django custom command ? -
Building a website using Python and Django
I am trying to build a website using Python and Django but I am not even able to print Hello World! I am able to get to the part where it says Django successfully installed though. It's what comes after is troubling me. I have been following many tutorials in youtube but to no avail I keep getting stuck at the same point. Can someone please guide me through this issue? I have attached screenshots of my progress. I am not able to understand the error either. Please help me out with this issue. [enter image description here] [enter image description here][1] [enter image description here][2] [enter image description here][3] [enter image description here][4] [enter image description here] [enter image description here][5] [enter image description here][6] Thanks and Stay Safe -
Getting a NameError while following django poll app tutorial
I am following django tutorial but i am getting a nameError. name Question is not defined from django.http import HttpResponse from django.http import HttpResponse def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output)