Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem regarding Installation of Pillow and zlib for PyCharm
When I am trying to install pillow it is saying "The headers or library files could not be found for zlib, a required dependency when compiling Pillow from source." And while I am trying to install 'zlib' its saying "Could not find a version that satisfies the requirement zlib (from versions: ) No matching distribution found for zlib" What to do. can anyone suggest please. I am using python3.8.2 in windown 10 Please help Its urgent -
Django Postgres memory leak
I have a custom Django command to start background job executers in a multi-threaded fashion which seems to give me memory leak issues. The command can be started like so: ./manage.py start_job_executer --thread=1 Each thread has a while True loop that picks up jobs from a PostgreSQL table. In order to pick up the job and change the status atomically I used transactions: # atomic transaction to temporary lock the db access and to # get the most recent job from db with column status = pending with transaction.atomic(): job = Job.objects.select_for_update() \ .filter(status=Job.STATUS['pending']) \ .order_by('created_at').first() if job: job.status = Job.STATUS['executing'] job.save() Il looks like the allocated memory by this Django custom command keeps growing. Using tracemalloc I tried to find what is causing the memory leak by creating a background thread that checks the memory allocation: def check_memory(self): while True: s1 = tracemalloc.take_snapshot() sleep(10) s2 = tracemalloc.take_snapshot() for alog in s2.compare_to(s1, 'lineno')[:10]: log.info(alog) Finding out the following log: 01.04.20 13:50:06 operations.py:222: size=23.7 KiB (+23.7 KiB), count=66 (+66), average=367 B 01.04.20 13:50:36 operations.py:222: size=127 KiB (+43.7 KiB), count=353 (+122), average=367 B 01.04.20 13:51:04 operations.py:222: size=251 KiB (+66.7 KiB), count=699 (+186), average=367 B 01.04.20 13:51:31 operations.py:222: size=379 KiB (+68.9 KiB), count=1056 … -
Opening browser in server from hosted Flask application in IIS not working
I am working on a flask application which needs to open a browser inside server and do some operations based on the user input. My application is working in visual studio and spyder. But when hosted it is not opening browser. I tried: webbrowser : Work in local but hosted code is not working pyppeteer : Work in local but hosted code is not working subprocess : Work in local but hosted code is not working I tried running a batch file from the hosted code to write into a file , this is working in local but the hosted code is not even running the subprocess. Can someone help on this? Thanks in advance! -
Fetch entire data from Celery task
I am currently using celery in my Django project. Below are my views.py and tasks.py files. views.py def status_codes(request): try: url = request.GET.get('url') urls = linksextraction(url) url_codes.objects.all().delete() for each_url in urls: res = url_status_codes.delay(each_url[1]) while (res.status == 'PENDING'):# waiting till all tasks are completed pass # Do manipulations from db data tasks.py @app.task def url_status_codes(url): r = requests.head(url) status_code = r.status_code spell_words = spellcheck(url, 'English--en') if (not spell_words): spell_words = 'NA' data = url_codes(status_code=status_code, url=url, spell_words=spell_words) data.save() # Saving in Database From above code snippets, I am saving results achevied in tasks.py in database and when all tasks are completed, i am fetching the results from db and doing manipulations. Is there any way to get all results in tasks.py to views.py without having saved to db. -
allauth is redirecting me to /accounts/profile when i am trying to go to /accounts/login
I have done all the necessary settings in settings.py, and i have set the urls too i the urls.py file. Each time i am trying to access /accconts/login, it will say the url did not match any pattern, and it redirects me to /accounts/profile. This are the code INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'core' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) SITE_ID = 1 urlpatterns = [ path('accounts/', include('allauth.urls')) ] -
django tutorial, not loading my static files properly
It's my fault I'm following different tutorials, but the first one worked well enough and figured I'd follow a more detailed one. Anyway, the first one had me move the templates folder outside the blog app and move it to the route, so I have the following on the settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] problem with that tutorial, it did not include any static setups for css and whatever static files I would need. That said, I'm following another tutorial that has me placed the css like so |- blog |---static |-----blog |-------main.css |- django_app |---all the settings found here |- templates |---blog |-----all my templates are here and had this on the base.html of the templates to <style rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"></style> but my template does not find it. I was able to trace my css through the following url http://127.0.0.1:8000/static/blog/main.css Idk what the best practice is with django and it's folder structure but any advice is appreciated. Thanks -
How to make jQuery script correctly run in google chrome?
I have django project and I can't make jquery script to run in google chrome. Simple code for checking if scroll is at bottom: <script language="JavaScript" type="text/JavaScript"> window.onload = function () { $('#scrolling').on('scroll', chk_scroll); }; function chk_scroll(e) { var elem = $(e.currentTarget); if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) { alert("bottom") } } </script> It works in Opera, Explorer, Firefox, Chrome (As single html file, not part of project), jsfiddle. P.s jquery loads correctly and other scripts works. -
Huey not calling tasks in Django
I have a Django rest framework app that calls 2 huey tasks in succession in a serializer create method like so: ... def create(self, validated_data): user = self.context['request'].user player_ids = validated_data.get('players', []) game = Game.objects.create() tasks.make_players_friends_task(player_ids) tasks.send_notification_task(user.id, game.id) return game # tasks.py @db_task() def make_players_friends_task(ids): players = User.objects.filter(id__in=ids) # process players @db_task() def send_notification_task(user_id, game_id): user = User.objects.get(id=user_id) game = Game.objects.get(id=game_id) # send notifications When running the huey process in the terminal, when I hit this endpoint, I can see that only one or the other of the tasks is ever called, but never both. I am running huey with the default settings (redis with 1 thread worker.) If I alter the code so that I am passing in the objects themselves as parameters, rather than the ids, and remove the django queries in the @db_task methods, things seem to work alright. The reason I initially used the ids as parameters is because I assumed (or read somewhere) that huey uses json serialization as default, but after looking into it, pickle is actually the default serializer. One theory is that since I am only running one worker, and also have a @db_periodic_task method in the app, the process can only … -
how to pass my_dict to redirect, like redirect('home',my_dict)
I want to pass this error into the template, but it is not working, def addcomment(request): name = request.POST['name'] comment = request.POST['comment'] if name=="" and comment=="": my_dict = {'error':'blank fields not allowed'} return redirect('home',my_dict) Comment(name = request.POST['name'],comment = request.POST['comment']).save() return HttpResponseRedirect('/') -
How to print value of a "changing field" in Django template
I am trying to display a list of fields (and their values) in a template. The problem is that the fieldnames are changing and I dont have control over them. e,g the fields can be: field_name1 field_object1 field_input1 The only thing constant here is the prefix "field_" This makes a challenge to get the value of that field in the template. I followed the advice here: Django: Cannot reference a fieldname in template which contains a dot and was able to print the field names. But i still dont know how to print the values of these fields. model.py rowObj = { 'id': id, 'inputList': {'Input_' + k: v for k, v in objList} } # Example of the outputs (The outputs can be one of the following): # rowObj = { # 'id': 1, # 'inputList': {'Input_Image' : 'http://test', # 'Input_Image2' : 'http://test2' } # } #another time the output can be: # rowObj = { # 'id': 1, # 'inputList': {'Input_Text' : 'Random text', # 'Input_Text2' : 'Random text 2' } # } My template is: {% for row in row_list %} <tr> <td>{{ row.id }}</td> {% for obj in row.inputList %} <td>{{ obj.value }}</td> {% endfor %} … -
Can Django run with failing database connection
Is it possible to handle a failed database connection but still have frontend run smoothly with Django? I wouldn't want my page break while the database stops. I'm using MySQL 5.7 and Django 1.8. -
Image ids apparently not being created
I have created a template for displaying a photo gallery and giving users the ability to add photos to that gallery. The idea is that there is an image associated with each comment - there is a for loop of {% for p in pictures %} at the start of the page, and I use variations of p. (e.g. p.image_id) to associate particular pictures with particular comments. In addition, the urls.py contains the following: path('add_comment/<int:p.image_id>', views.add_comment, name='add_comment') However, when I run the code, I get an error message that suggests that image ids aren't being created (even though image is a field in he Pictures model I created): Reverse for 'add_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['add_comment/$'] What do you suggest, please? -
Django's dbshell and sqlmigrations
The output of the initial default sqlmigrate from Django works when running it with manage.py but applying the output of sqlmigrate does not work with sqlplus [the default for manage.py dbshell]. When creating triggers (e.g) select count from user_sequences loop is terminated by a /; could this be the issue? I've searched through the source code but cannot understand how Django is applying these differently than using its shell and sqlmigrate. -
How to slove a MultiValueDictKeyError in Djangos Rest API upload?
I am currently setting up a file upload with React for the frontend and Django for the backend. I want to upload a file and some jason data. When submitting the data to my django backend i get the following error message: raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'data' The error message refers to 'data' in the utils.py file, wehere I define my multipart parser. models.py (Django) class Story (models.Model): title = models.CharField(max_length=100,blank=False) content = models.TextField(blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) audio = models.FileField(default='SOME STRING', upload_to='audio_stories/',null=True, validators=[validate_file_extension_audio]) def __str__(self): return self.title def get_absolute_url(self): return reverse('story-detail', kwargs={'pk': self.pk}) serializers.py (Django) class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = '__all__' A MultiPartParser is used to pass file + data. api.py (Django) class StoryViewSet(viewsets.ModelViewSet) (Django): serializer_class = StorySerializer parser_classes = (MultipartJsonParser, parsers.JSONParser) queryset = Story.objects.all() permission_classes = [ permissions.IsAuthenticated ] def perform_create(self, serializer): serializer.save(author=self.request.user) utils.py (Django) class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # find the data field and parse it data = json.loads(result.data["data"]) qdict = QueryDict('', mutable=True) qdict.update(data) return parsers.DataAndFiles(qdict, result.files) In actions story.js (React) import axios from "axios"; import { tokenConfig } from './auth'; import { createMessage, returnErrors } from "./messages"; import {ADD_STORY} … -
set django setting django-graphql-jwt samesite options
I'm trying to make an authentication system for my react front-end i want to use cookie authentication for it but i cant set cookies SameSite attribute i couldn't find anything on package's site isn't there any setting for it ? https://django-graphql-jwt.domake.io/en/latest/settings.html like that ? """JWT_COOKIE_SECURE = True""" Can anyone help me ? -
Django: strange filtering Database for None-Values behaviour
I'm facing a very strange situation when making a Database Request from Django. I have a model, chat, wich has a field named expired, which can be null. The goal is to filter all the elements from the Chat-Database where expired is not None. Running the following quick test: for chat in Chat.objects.all(): print(chat.expired is None) gives me: True True True True True False So there are Chat-objects which expired-fields are not none. But when filtering: print(Chat.objects.filter(expired__isnull=False)) it gives me: <QuerySet [<Chat: 1, type: G>, <Chat: 2, type: G>, <Chat: 3, type: G>, <Chat: 4, type: G>, <Chat: 5, type: G>, <Chat: 6, type: P>]> while the following: print(Chat.objects.filter(expired__isnull=True)) gives: <QuerySet []> Both Query outputs cant be right, since in the first test we can see that there are 6 Chat-objects, not all with expired-fields set to None, but the first Query gives six Elements. The second gets Zero, although there are elements with expired-fields to None. What is the Problem? Thanks in Advance! Edit The Model: class Chat(models.Model): TYPE_CHOICES = [ ('P', 'private'), ('G', 'group'), ] name = models.CharField(max_length=100, default="private") type = models.CharField(max_length=2, choices=TYPE_CHOICES, default='P') image = models.ImageField(null=True, blank=True) expired = models.DateTimeField(null=True, blank=True) -
serialize model to use with Chart.js in Django
even though I have seen a lot of resource about similar topics, nothing has been to solve my issue. the closest were How do I JSON serialize a Python dictionary? and django model serialization. I am trying to plot a model on my frontend with Chart.js and I cannot get my view to be serialized yet being able to fit the arguments for the graph to know what needs to be plotted. I attach my model.py, view.py and htlm page as well as the error that I get. models.py class Classification(models.Model): Class = models.CharField(max_length=10, primary_key=True) inventory_dollars = models.FloatField(default=0) def __str__(self): return self.Class class ClassificationSerializer(serializers.ModelSerializer): class Meta: model = Classification fields = "__all" views.py class HomeView(View): def get(self, request, *args, **kwargs): return render(request, 'dashboard/charts.html', {}) class ChartData(APIView): authentification_classes = [] permission_classes = [] def get(self, request, format=None): labels = Classification.Class default_items = Classification.inventory_dollars data = { "labels" : labels, "default": default_items } return HttpResponse(json.dumps(data), content_type = 'application/javascript; charset=utf8') html {% extends 'dashboard/base.html' %} <script> {% block jquery %} var endpoint = '/api/chart/data' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data1){ labels = data1.labels defaultData = data1.default setChart() }, error: function(error_data){ console.log(error_data) }} ) function … -
How to render a js function that comes from django view as str?
I'm trying to implement a payment api to my django project. The api returns a dict when i send a request. The content of dict is like that; ...'checkoutFormContent':'<script type="text/javascript">if ...</script>'... How to render this js function in my template? -
Django - How to capture & record selected images
I am trying to filter out inappropriate images using a visual interface. Inappropriate images are subjective, which is why I want a user to select only the appropriate images (selecting multiple at a time) and press 'Finish' once selection is complete. The user's inputs should be stored in the database similar to this: user_x = image1, image2, image4 ...... user_y = image6, image2, image3 ...... . . Here's what it currently look's like: Image Filtration I am a complete beginner to Django and I am not sure how to do this. Any help would be greatly appreciated. filter.html (Template to display images) <div class="container-fluid my-container"> {% filter_images_normal 3 as images %} <div class="row no-pad display-flex my-row"> {% for image in images %} <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col- my-col my-col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4 my-col"> <input class="img-thumbnail" type="image" id="image" alt="Image" src="{{ MEDIA_URL}}{{ image }}"> </div> {% endfor %} </div> <button type="button" class="btn btn-primary btn-lg btn-block">Finish</button> </div> filter_images.py (template tag to select distinct random images from folder) @register.simple_tag def filter_images_normal(count=3): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_filter/images/normal/' path = '/app_filter/static/app_filter/images/normal/' files = [f for f in os.listdir(settings.BASE_DIR + path) if f[f.rfind("."):] in valid_extensions] # print(random.sample(files, count)) print(rand_dir) return [rand_dir … -
saving the form data into db using django modelforms
I want to save the model form data into database. But whatever data is enter on the form it is not throwing any error it is showing same page. I just add the csrf_token into template. because i have model form and it is showing proper template. but data is not saving through template page. Here is my View: def auth_register(request): form = forms.SignUpForm() if request.method == 'POST': form = SignUpForm(request.POST or None) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = Register(first_name=first_name, last_name=last_name, email=email, password=password) user.save() messages.success(request, 'Form submission successful') return HttpResponse('data has been saved :') return render(request, 'auth-register.html', {'form':form}) Model snippet is: class Register(models.Model): first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) email = models.EmailField(max_length=50, blank=False) password = models.CharField(max_length=12, blank=False) Forms snippet is : class SignUpForm(forms.ModelForm): class Meta: model = Register fields = ['first_name','last_name','email','password'] Template is : <body> <form action="" method="post"> {%csrf_token%} <div class="loader"></div> <div id="app"> <section class="section"> <div class="container mt-5"> <div class="row"> <div class="col-12 col-sm-10 offset-sm-1 col-md-8 offset-md-2 col-lg-8 offset-lg-2 col-xl-8 offset-xl-2"> <div class="card card-primary"> <div class="card-header"> <h4>Register</h4> </div> <div class="card-body"> <form method="POST"> <div class="row"> <div class="form-group col-6"> <label for="frist_name">First Name</label> <input id="frist_name" type="text" class="form-control" name="frist_name" autofocus=""> </div> <div class="form-group … -
replace() takes no keyword arguments
I'm trying to find the first day of the month in python from_date = to_date.replace(day=1) but i got this error : replace() takes no keyword arguments -
Django: Signal not automatically not creating attribute to User
I have a problem using Djangos Signals while creating a User and a Profile. I'm trying to create a Profile upon creating a User, but I keep getting the error: AttributeError at /user/create/ 'User' object has no attribute 'profile' So here is my User Model: from django.db import models from django.contrib.auth.models import AbstractUser from django_countries.fields import CountryField class User(AbstractUser): """auth/login-related fields""" is_a = models.BooleanField('a status', default=False) is_o = models.BooleanField('o status', default=False) def _str_(self): return "{} {}".format(self.first_name, self.last_name) and here is my Profile Model: from django.db import models from django_countries.fields import CountryField from django.contrib.auth import get_user_model User = get_user_model() from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): """non-auth-related/cosmetic fields""" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='Profile') birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) nationality = CountryField(null=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) def __str__(self): return f'{self.user.username} Profile' My User Serializer: from rest_framework import serializers from django.contrib.auth import get_user_model from ..models.model_user import * class UserIndexSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', 'password', 'first_name', 'last_name', 'email', 'is_a', 'is_o' ] class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', 'password', 'first_name', 'last_name', 'email', 'is_a', 'is_o' ] extra_kwargs = {'password': {'write_only': True}} def create(self, … -
Django website deployement debug= false cause template error
i am trying to host a django ebsite.And i set debug-false on settings.py,when i load my website it have probblem on template.templates allignments are not in correctorder.anybody please help me to solve it? -
Change E-mail configuration in setting.py
I have configuration to e-mail in setting.py: EMAIL_HOST = 'Host' EMAIL_PORT = 'NrPost' EMAIL_HOST_USER = 'User' EMAIL_HOST_PASSWORD = 'Pass***' EMAIL_USE_TLS = True EMAIL_USE_SSL = False And with correct data it work. But now I have data in DATABASES. Where I can change value email_host etc. from database? -
How can Get two fields in one Model.py by use foreign key in django
**> How can Get two fields in one Model.py by use foreign key in django? > I want Fields are Course_Name, Branch_Name in Institutes Model and Show My other Courses Model** **This is the Model one >>>** ''''' class Institutes(models.Model): InstituteNo = models.AutoField(primary_key=True) Institute_Name = models.CharField(max_length=300) Course_Name = models.CharField(max_length=300) Course_Code = models.CharField(max_length=100) Branch_Name = models.CharField(max_length=300) Branch_Code = models.CharField(max_length=100) Course_Duration = models.CharField(max_length=100) '''' **#How can Retun Two Fieldsclass Meta: And def __str__(self): only one Value is show in Both Columns.** ''' class Meta: verbose_name_plural = "CourseName" def __str__(self): return self.Course_Name ''' This is the Model two ''' class Courses(models.Model): CourseNo = models.AutoField(primary_key=True) Institute_Name = models.ForeignKey(Facultys, verbose_name="Institute Name", default="0", on_delete=models.CASCADE) Course_Name = models.ForeignKey(Institutes, related_name="CourseName", default="0", on_delete=models.CASCADE) # Show one Filed Here Branch_Name = models.ForeignKey(Institutes, related_name="BranchName", default="0", on_delete=models.CASCADE) # Show Seccond Filed Here Year_or_Sem = models.CharField(max_length=100) ''' **> the output is show same value both drop down...but i want both drop down value Course_Name, Branch_Name**