Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Handling multiple calls to an API django
I'm hosting an API that will be subjected to multiple users to call it at the same time. Each call will take around 10 seconds to return as I will be running some GPU computations and returning the request. 1) How do I test how many GPU cores a require to return X number of requests? 2) I tried calling 2 calls simultaneously and it is able to compute both requests, how do I test how many requests it can handle at one go. Do I need a request manager to queue thee jobs? (currently my machine only has one GPU core) 3) How does API handle multiple requests in general? Thanks for helping! -
SQL query is working directly but not when called from Python (django)
from django.db import connections with connections['DB'].cursor() as cursor: select_query = "select * from <table_name> where <condition_row> like '<PRODUCT_NAME>%' and creation_date like '" + today_date + "%';" cursor.execute(select_query) today_date = (datetime.date.today() - datetime.timedelta(1)).strftime("%d-%m-%y") The select query when executed directly from SQL developer gives output . But when called from the above script is giving null output . -
How to write a Query for getting a stock statement in django
I am just learning django for past few weeks.I wanna know how to write stock statement query in django? for example A=incoming products B= outgoing products stock = A-B I been creating a app for my warehouse business struck in here need help ! enter image description here so the image shows the models of the app ..what i want to accomplish is to add a query to views that brings stock statement -
Is it okay to use Postman to Profile Response Time of Django Endpoints?
I have been searching for ways to profile Django endpoints using Postman but I did not see any post about it. Is it okay to use Postman to Profile Response Time of Django Endpoints? (Currently, I have been profiling it by running the request five times then doing the average. Is this a good idea?) -
How to I automatically filter out is_deleted records in an associated table in Django?
I am using soft deletes on one of my models in Django, and I am overwriting the default manager to always return active records only, using something like: class ActiveRecordManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_deleted=False) class Tag(models.Model): is_deleted = models.BooleanField(default=False, db_index=True) objects = ActiveRecordManager() class Photo(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE, related_name="photos") objects = ActiveRecordManager() All works well. However, when I do: tag = Tag.objects.get(pk=100) And then I try to get the associated photos: photos = tag.photos.all() Then I get photos that are deleted. I only want to return objects that are not deleted (so my regular objects list. I was reading about _base_mangers in Django, which seems to control this, but the documentation recommends against filtering objects out: If you override the get_queryset() method and filter out any rows, Django will return incorrect results. Don’t do that. A manager that filters results in get_queryset() is not appropriate for use as a base manager. But what I am not clear about is how I am supposed to filter these results. Any thoughts? -
Has anyone tried django-friendship package? [closed]
I recently installed this package to my site to add a follower system but is not working or i miss to add something. The button to follow a user is not working. I have tried this to follow a user and then show my following list but is not working: views.py from django.contrib.auth.models import User from friendship.models import Friend, Follow, Block class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name='posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['users'] = User.objects.exclude(id=self.request.user.id) context['following'] = Follow.objects.following(self.request.user) def change_follower(request, operation, pk): follow = User.objects.get(pk=pk) if operation == 'add': Follow.objects.add_follower(request.user, other_user, follow) elif operation == 'remove': Follow.objects.remove_follower(request.user, other_user, follow) return redirect(request.META['HTTP_REFERER']) urls.py from django.urls import path, re_path from .views import PostListView from . import views app_name='blog' urlpatterns = [ re_path(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.change_follower, name='change_follower'), ] Html <article class="featured-user"> <div class="row row-st-user"> {% for user in users %} <div class="col-auto user-col-feautered"> <div class="follow-user-span"><span>&nbsp;<img class="featured-user-img" src="{{ user.profile.image.url }}"><span class="user-feauter-st">{{ user.username }}</span></span> </div> {% if user in following %} <div class="div-user-follow"><a href="{% url 'blog:change_follower' operation='remove' pk=user.pk %}"><button class="btn btn-success btn-sm following-button-st-user" type="button">FOLLOWING</button></a></div> {% elif not user in following %} <div class="div-user-follow"><a href="{% url 'blog:change_follower' operation='add' pk=user.pk %}"><button class="btn btn-success btn-sm follow-button-st-user" type="button">FOLLOW</button></a></div> {% endif … -
django.db.utils.DataError: value too long for type character varying(10)
I am using Array Field in my django app but when I try to enter a value (for e.g. Andaman and Nicobar Island) in it it throws the following error: django.db.utils.DataError: value too long for type character varying(10) Here's my models.py states_dealtin = ArrayField( models.CharField(max_length=255, blank=True) ) The length is not exceeding 255 characters the why is it showing the error? -
Django database (Postgresql) sync for offline android
I have already have online website that converted to android app, i just want to know if it is possible to if the users(offline android) can add and update their local database. and when that users back to online what he has been add or update on their local database is synchronized back to the online server. django postgres android studio -
Django and Data Processing
I have a csv file uploaded to Django WebServer via POST method in Form on my page. This data are going to be converted to DataFrame, compared with some other data taken from DB Server and returned to the user as downloadable csv file. This All happens on my WebServer and it makes processor very busy for some time - I can't image what happens, when more users make same processing at the same time. I would like to distribute processing to the more cpu cores or if possible to more servers. I don't know why, but Django with Apache doing this processing on one core and is not willing to use more. Is there a way to multi-process this stuffs? Or even distribute to more servers to processing? I'm considering to use PySpark but I'm not sure if it is a good way to do it... (I have never used PySpark before) -
Django rest framework prefetch_related and select_related doesn't work
I'm try to decrease query counts for using prefetch_related and select_related. However, it seems doesn't work I can't find where I'm doing wrong. Models.py class Tournament(models.Model): name = models.TextField(blank=False, null=False) ... game = models.ForeignKey(Game, on_delete=models.SET_NULL, null=True) class Match(models.Model): name = models.TextField(blank=False, null=False) game = models.ForeignKey(Game, on_delete=models.SET_NULL, null=True) tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True, blank=True) .... serializers.py class TournamentSerializer(serializers.ModelSerializer): game = GameSerializer(many=False, read_only=True) ... match_name = TournamentMatchSerializer(many=True, source='match_set') class Meta: model = Tournament fields = '__all__' class TournamentMatchSerializer(serializers.ModelSerializer): class Meta: model = Match fields=['name'] views.py class TournamentDetailAPIView(RetrieveAPIView): queryset = Tournament.objects.all().prefetch_related(Prefetch('Match',queryset=Match.objects.select_related('tournament'))) serializer_class = TournamentSerializer -
Django/Python - Not able to display result in line by line and with filename
urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('VRFFILELIST/',views.sindex,name="Home-Page"), ] forms.py: ========== from django import forms class stringform(forms.Form): Enter_VRF_Name_To_Search = forms.CharField(max_length=20) views.py =========== from django.shortcuts import render from .forms import stringform import os def sindex(request): search_path = "C:/AUTOMATE/STRING/TESTFILE/" file_type = ".txt" Sstringform = stringform() Scontext = {'Sstringform' : Sstringform} if request.method == 'POST': SVRFTEXT = Scontext['Enter_VRF_Name_To_Search'] = request.POST['Enter_VRF_Name_To_Search'] #fname1 = [] ftext = [] Scontext['resultlist'] = ftext for fname in os.listdir(path=search_path): fo = open(search_path + fname) fread = fo.readline() line_no = 1 while fread != '': fread = fo.readline() if SVRFTEXT in fread: ftext.append(fread) line_no +=1 fo.close() return render(request, 'demoapp/VRFFILELIST.html', Scontext) VRFFILELIST.HTML =================== <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>VRF FILE LIST</title> </head> <body> <form method="POST"> {% csrf_token %} <table> {{Sstringform.as_table}} </table> <button type="submit">Send Command</button> </form> <table> <h3>VRF IN LIST OF FILES</h3> <textarea rows="20" cols="80" name="conf" form="conf" id="conf">{{resultlist}}</textarea> </table> </body> </body> </html> Output: [' ip vrf forwarding TEST:VRFA\n', ' ip vrf forwarding TEST:VRFA\n', ' address-family ipv4 vrf TEST:VRFA\n', ' neighbor 10.10.10.1 route-map TEST:VRFA-IN in\n', ' neighbor 10.10.10.1 route-map TEST:VRFA-OUT out\n', ' ip vrf forwarding TEST:VRFA\n', ' neighbor 192.168.10.2 route-map TEST:VRFA-IN in\n', ' neighbor 192.168.10.2 route-map TEST:VRFA-OUT out\n'] Required Output: TEST-FILE-A: ip … -
How do i deny access to admin page in Django 3.0?
I want it so that when a non staff/non admin/non superuser tries to access the django admin page, it raises a 404 error and when a user is staff/admin/superuser it directs to the login for the admin page. def nonstaffuser(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_superuser: return view_func(request, *args, **kwargs) else: raise Http404 return wrapper_func This is the decorator I made. urlpatterns = [ path('admin/', nonstaffuser(admin.site.urls)) ] I imported the decorator and it does raise a 404 when a user isn't staff but when a user is actually a staff/admin/superuser it raises a error: 'tuple' object is not callable. How do I fix this? Thank You -
when i input right information to login, it always return fail in django
I'm doing my project. Make my own model, and signup and signin. I successed signup. but when i signin, it always fail. what is wrong with my code? model.py from django.contrib.auth.models import(BaseUserManager, AbstractBaseUser, PermissionsMixin) from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, username, userid, company, companycode, password=None): if not username: raise ValueError(_('Users must have an name!')) user = self.model( username=username, userid = userid, company= company, companycode = companycode, ) user.save() return user def create_superuser(self, username, userid, company, companycode, password): user = self.create_user( username=username, userid = userid, company = company, companycode = companycode, password=password, ) user.set_password(password) user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=10, unique=True, verbose_name="이름") userid = models.CharField(max_length=100, unique=True, verbose_name="아이디") company = models.CharField(max_length=10, verbose_name="회사") companycode = models.CharField(max_length=100, verbose_name="회사코드") created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜") is_admin = models.BooleanField(default=False) #is_active = models.BooleanField(default=True) class Meta: db_table = 'user' objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['userid', 'company', 'companycode'] def __str__(self): return self.username def get_full_name(self): return self.username def get_short_name(self): return self.username @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All superusers are staff return self.is_superuser get_full_name.short_description = _('Full name') views.py from django.contrib.auth.models … -
How do i include Cloudinary API key in Django code?
** As of now am Providing API key externally by using command ** set CLOUDINARY_URL=cloudinary://API-KEY:API-SECRET@Cloudname But every time it is not possible in global deployment -
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