Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to sum values in an HTML table column
I have checked every conceivable questions available on SO but did not find one that solved my problem. The closest I got was on this. In my Django app I have a dynamic table with columns for price, quantity and amount (price * quantity) besides other fields. I am looking to get the sum total of "amount" column. Rows can be added at runtime and for my test purpose I have kept the default number of rows to 3 (extra = 2 in inlineformset_factory). I am using the following jquery for the purpose of calculating values in "amount" column: $(document).ready(function() { mySum=0; $("#process").click(function() { $(".itemPriceClass").each(function() { mySum += parseFloat($('.itemPriceClass input').val()); alert('The sum of item amount is: ' + mySum); }); }); }); where: "itemPriceClass" is <td> class in the Amount column. "process" is the id of a button to get the function to execute. However, when executed (with the default three rows of the table and only the first row having been filled in), I find that the function is executed three times (though the last two rows do not have any data in them) and the final total comes to exactly three times the value in that of the … -
Effeciant way to load images from directory using django template
I have hundreds of images under /statics/projectname/*.png , usually i load the images like following. {% extends "base.html" %} {% load static %} {% load staticfiles %} {% for result in projects %} <div class="banner-img"> <img src="{% get_static_prefix %}/{{result.project_name}}/{{ result }}.png" alt="Image 1"> </div> {% endfor %} But i noticed that it is time consuming task, app takes enough time to load the images and render. What is the most effecient and faster way to fix this. -
When i run the scrapy its shows an error like __import__(name) ImportError: No module named home in ubuntu
when i run the scrapy it shows an error like, import(name) ImportError: No module named home,how to solve this issue? import os import sys import django DJANGO_PROJECT_PATH = '/home/user/Documents/myproject' DJANGO_SETTINGS_MODULE = 'myproject.settings' sys.path.insert(0, DJANGO_PROJECT_PATH) os.environ['DJANGO_SETTINGS_MODULE'] = DJANGO_SETTINGS_MODULE BOT_NAME = 'example_bot' django.setup() -
To create multiple Django projects on one virtual environment , is this good or bad
To create multiple Django projects on one virtual environment , is this good or bad ! i am a beginner in Django Python... -
Is there an app for Django to manage fields of models?
Like in phpmyadmin, we have an visual interface to manage fields. Can we do the same thing in Django? -
group by two varlues and get the third values
I have this Django model with three CharFields, which I want to run a query on to get the existing values for the two of them, and for each combination get the existing values of the third field. a = models.CharField(null=False, max_length=8000) b = models.CharField(null=False, max_length=8000) c = models.CharField(null=False, max_length=8000) if assume that these values are in the database: a | b | c | --------------- a1 | b2 | c3 | a1 | b2 | c1 | a2 | b2 | c3 | a1 | b3 | c3 | a1 | b2 | c2 | I want some result in this form : {"a1-b2" : [c3, c1, c2], "a2-b2" : [c3], "a1-b3" : [c3]} or {"a1" : {"b2":[c3, c1, c2], "b3": [c3]}, "a2": {"b2" : [c3]}} -
django.contrib.sites table can not find in xadmin
I relpaced admin with xadmin,however sites app in admin instead of xadmin i want to know the reason,thanks! -
Django Connect remote Mysql OperationalError 2026
I'm using Django + mysql for days. And this morning I suddenly found that I cannot get connect with the remote mysql. % python manage.py makemigrations it raise django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') also when python manage.py runserver Here's my environment: macOS 10.15 + Django 2.2.6 + MySQL 5.7 (on a remote server, ubuntu 18.04) + python 3.6.8 (use conda env) I've looked for some solutions like: downgrade openssl Package openssl conflicts for: openssl=1.0.2r python=3.6.8 -> openssl[version='>=1.1.1a,<1.1.2a'] add use_pure=True in my .conf file nothing changed add skip_ssl in my .conf file nothing changed note On the server (which I deploy my site, ubuntu 18.04) my site run well using gunicorn + Nginx All the things worked well until today. The site broke when I found this issue but work well when I restart it. I guess maybe some update on the server (automatically upgrade) to cause the problem, but haven't find it yet. some of my code # setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': mysqlPath, 'init_command': 'SET default_storage_engine=INNODB', }, } } # my_remote.cnf (which define the 'mysqlPath' in setting.py) [client] database = mydatabase user = myusername password = mypassword default-character-set = utf8 host … -
How to track the value of a variable that is updated per view and in a loop?
In my app I am querying an external API that has a rate limit of 600/30000 requests per 15 minutes/day. I want to be able track - from any place in my app at any time - how many requests are left for my app. Suppose I have defined REQUESTS_LEFT variable somewhere in my app for this purpose. But now imagine that my view does multiple requests in a loop and diminishes the value of REQUESTS_LEFT on every request: def API_requests(request): for i in range(50): make_API_request() # some function making request to external API REQUESTS_LEFT -= 1 return HttpResponse('Done!') If this view is called again, the loop from the previous view call will still be running, introducing a race condition where both the old and the new loop will be updating the value of REQUESTS_LEFT (the new loop starting where the old loop was when the view was called again). As a result the variable REQUESTS_LEFT becomes useless. What would be a better way to approach this? -
NoReverseMatch at / 'celery_progress' is not a registered namespace
I'm trying to integrate this library into my django app on heroku. It's giving me this error: NoReverseMatch at / 'celery_progress' is not a registered namespace Index.html(where the error occurs): // vanilla JS version document.addEventListener("DOMContentLoaded", function () { var progressUrl = "{% url 'celery_progress:task_status' task_id %}"; CeleryProgressBar.initProgressBar(progressUrl); }); Any ideas? -
Django OAuth with Non-Social Provider
I have an application for which I'd like to make use of SSO which is supplied by many schools and companies via OAuth. There are existing plugins for Github, Google, Facebook, Twitter and the likes but I can't seem to find anything regarding these other providers. Is there any way to go about this? -
How to mysql config in django setting
I tried to connect MySQL in Django. but it's throwing an error on django.db.utils.OperationalError: (1044, "Access denied for user ''@'localhost' to database 'yourdbname'") how to solve this error . Setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'yourdbname', 'HOST': '127.0.0.1', 'PORT': '3306', }, } I tried to different ways to solve this issue. but it's not working This is first time I am working on muysql to connect django. -
How to send files from NodeJs to Django app using axios?
Am trying to send files from Nodejs app to Django app, but when I try to test if the file is sent, it shows that there is no files! Nodejs: appJ.get("/testFiles", (req, res) => { var formData = new FormData(); formData.append("file", fs.createReadStream('src/assets/TextFiles/104931574076657597.txt')); axios.post("http://127.0.0.1:8000/testFile/", formData).then(result => { console.log(result.data); }).catch(err => { console.log(err); }) }) Django: @csrf_exempt def testFile(request): if (request.method == "GET"): return HttpResponse("Ok") elif(request.method == "POST"): print("Hello") print(request.FILES) return HttpResponse("OK") How can I solve that? -
Recebendo "Login timeout expired" MS SQL Server + Python Django
Tenho um banco de dados SQL Server instalado no windows e gostaria de acessa-lo através do código que estou desenvolvendo em minha máquina virtual que roda Ubuntu (python + django + django-pyodbc-azure + pyodbc) Tentei praticamente todos os procedimentos que encontrei em minhas pesquisas mas não obtive sucesso. O banco de dados está acessível através da rede local uma vez que consigo acessa-lo através de um app no celular. O que me leva a crer que pode ser um problema relacionado ao ambiente ubuntu ou alguma configuração do vmware. A conexão com a rede dessa máquina virtual está no modo bridge": Windows: 10.0.1.190 Ubuntu: 10.0.1.191 Essa é a configuração que estou colocando no settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': "10.0.1.190", 'USER': "usuario", 'PASSWORD': "senha", 'NAME': "nomedobanco", 'PORT': "1433", 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } } Este é o erro que estou recebendo: django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') Ping do ubuntu pro windows: ''' rpinheiro@ubuntu:~$ ping 10.0.1.190 PING 10.0.1.190 (10.0.1.190) 56(84) bytes of data. From 10.0.1.191 icmp_seq=1 Destination Host Unreachable From 10.0.1.191 icmp_seq=2 Destination Host Unreachable ''' Alguma ideia? -
How do I use AJAX to both create and edit new posts using the same html template (with Python & Django)?
I'm trying to switch to saving a form with AJAX instead of just Python/Django (I'm an absolute newb, so please forgive my idiocy). Here's what I'm trying to achieve: urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.blurb_new, name='blurb_new'), path('blurb/new/', views.blurb_new, name='blurb_new'), path('blurb/<int:pk>/edit/', views.blurb_edit, name='blurb_edit'), ] views.py (the relevant part): @login_required def blurb_new(request): if request.method == "POST": form = BlurbForm(request.POST) if form.is_valid(): blurb = form.save(commit=False) blurb.author = request.user blurb.save() return redirect('blurb_edit', pk=blurb.pk) else: form = BlurbForm() return render(request, 'mysite/blurb_edit.html', {'form': form}) @login_required def blurb_edit(request, pk): blurb = get_object_or_404(Blurb, pk=pk) if request.method == "POST": form = BlurbForm(request.POST, instance=blurb) if form.is_valid(): blurb = form.save(commit=False) blurb.author = request.user blurb.last_edited_date = timezone.now() blurb.save() return redirect('blurb_edit', pk=blurb.pk) else: form = BlurbForm(instance=blurb) return render(request, 'mysite/blurb_edit.html', {'form': form, 'blurb': blurb}) blurb_edit.html (the relevant parts): <form id="myform" method="POST" class="blurb-form">{% csrf_token %} <input id="blurb-name" name="title" {% if form.title.value != None %}value="{{ form.title.value }}"{% endif %} /> <textarea name="text" id="my-textarea"> {% if form.text.value != None %} {{ form.text.value }} {% else %} Type your blurb here. {% endif %} </textarea> <button type="submit">Save</button> </form> Before I used AJAX, views.py was totally doing its job (except for that pesky, unwanted page refreshing). Because I hate the way … -
How to create and start a form Select field, without it being in the model?
I have reviewed many of the questions related to this topic, in this forum and in Spanish, I have followed the steps, and it does not work for me, on something that seems so simple, at first. I have Django 2.2.6 with a form that needs the selected value of a Select field, which is not in the model, and acquires a list of values (tuples of two) created from the view. Upon entering the form, throw this error: "__init __ () received an unexpected keyword argument 'carpetas'", in the FotoArtForm class, in the super () line. This is my code: models.py class FotoArt(models.Model): nombre = models.CharField(max_length=50) foto = models.ImageField(upload_to='fotos/articulos/', null=True, blank=True) class Meta: ordering = ['nombre'] verbose_name = _('Foto Artículo') verbose_name_plural = _('Fotos Artículos') def __str__(self): return self.nombre def get_absolute_url(self): return reverse('detalle-fotoArt', args=[str(self.id)]) views.py class FotoArtActualizar(LoginRequiredMixin, UpdateView): model = FotoArt form_class = FotoArtForm Ruta = os.path.join(MEDIA_ROOT, 'fotos', 'articulos') def get_form_kwargs(self): kwargs = super(FotoArtActualizar, self).get_form_kwargs() kwargs['carpetas'] = self.get_folders_list(self.Ruta) return kwargs def get_folders_list(self, ruta): foldersList = [] for _, listaSubDir, _ in os.walk(ruta): for dName in listaSubDir: foldersList.append((dName, dName)) return foldersList forms.py class FotoArtForm(forms.ModelForm): guardar_en_carpeta = forms.ChoiceField(choices=(), required=True) def __init__(self, *args, **kwargs): super(FotoArtForm, self).__init__(*args, **kwargs) self.foldersList = kwargs.pop('carpetas', None) self.fields['guardar_en_carpeta'].choices = … -
Outerref and Subquery not retrieving datetime data
I have a use case where I am trying to calculate the total value of some transactions given amount and historical price, with the following models: class Transaction(models.Model): ... asset = models.ForeignKey('Asset', ...) amount = models.FloatField() date = models.DateTimeField() ... class Price(models.Model): ... asset = models.ForeignKey('Asset', ...) price = models.FloatField() date = models.DateTimeField() ... What I am trying to do, it get all the Transactions, through a query and annotate the historical price through a Subquery : from django.db.models.expressions import Subquery, OuterRef price_at_date = Price.objects.filter( date=OuterRef('date'), asset=OuterRef('asset')).values('price') transactions = Transaction.objects.filter(...).annotate(hist_price=Subquery(price_at_date)) This returns None for hist_price. I suspect it has something to do with the fact that the datetimes do not match, (different time but same date). I tried to replace any combination of date by date__date but this still does not work and returns None in hist_price. Any idea how I can get the historical price for the same date (but not time) though the Django ORM / query ? Thank you! -
Django OneToOneField self-referential in save method
I have the following (simplified version): class Model: reference = models.OneToOneField(to='self', on_delete=..., related_name='referenced_field') Now, on another instance of Model I do: a = Model.objects.create(...., reference=Model.objects.get(id=request.POST.get('reference_id')) Now, I've modified the save method so that when I edit object a I can update a common field that's reflected in reference. def save(.....): self.referenced_field.common_field = .... However, this raises a DoesNotExist saying the referenced_field reverse relationship is non-existent.... And yet I'm staring at the filled out field in the database. Bug or am I missing something? -
Adding an inline in the Django admin that is a ManyToMany which is using a custom through table
I am using django-ordered-model to add order to my models. I've had to use a custom through table so that things are ordered correctly. Everything is working fine at the moment except when it comes time to add the many to many relations to the admin. I would like to be able to select the toppings in the Pizza object view in the admin. # models.py from django.db import models from ordered_model.models import OrderedModel class Topping(models.Model): name = models.CharField(max_length=255) class ToppingThroughModel(OrderedModel): pizza = models.ForeignKey('Pizza', on_delete=models.CASCADE) topping = models.ForeignKey('TestTable', on_delete=models.CASCADE) order_with_respect_to = 'pizza' class Meta: ordering = ('pizza', 'order') class Pizza(models.Model): name = models.CharField(max_length=255) toppings = models.ManyToManyField('Topping', through='ToppingThroughModel', blank=True) I thought something like the following would work, but it does not. # admin.py from django.contrib import admin from app.models imprort Pizza, Topping class ToppingInline(admin.TabularInline): model = Pizza.toppings.though extra = 1 class PizzaAdmin(admin.ModelAdmin): inlines = [ToppingInline] -
Was creating model.manager and I believe I deleted the database
I am using Django 2.2.7, python 3.7.4 and windows 10. I am following django docs to create a project. I wanted to create a Queryset but I want to use my field names vs objects. By following tutorial, I created model.Manager (or so I thought). I executed python manage.py makemigrations and python manage.py migrate but in the migration file it appears I have deleted fields and maybe the DB, I'm not sure. What I was attempting is: DB name :district change the two field names ("congressional_district and zcta) from "objects" and instead use their names in the Manager model to call specifically. Did I confuse myself? from django.db import models class district(models.Model): congressional_district = models.IntegerField(default=0) zcta = models.IntegerField(default = 0, primary_key=True) #can integers be limited like Charfields? congressional_district = models.Manager() zcta = models.Manager() def __str__(self): return f'{self.congressional_district} {self.zcta}' ``` Migration file operations = [ migrations.AlterModelManagers( name='district', managers=[ ('congressional_district', django.db.models.manager.Manager()), ], ), migrations.RemoveField( model_name='district', name='congressional_district', ), migrations.RemoveField( model_name='district', name='zcta', ), migrations.AddField( model_name='district', name='id', field=models.AutoField(auto_created=True, default=django.utils.timezone.now, primary_key=True, serialize=False, verbose_name='ID'), preserve_default=False, ), ] -
Using Celery with Split Settings Folder
I inherited a project and the folder structure is confusing to me. I've used celery and django together before, but I always had one settings file and the structure was different. I'm having issues making this run and the documentation uses the traditional folder structure. Help would be greatly appreciated. Folder structure |Project |app1 |app2 |tasks.py |settings |__init__.py |apps.py |dbs.py |middleware.py |celery_config.py |__init__.py |celery.py |manage.py |urls.py |views.py |wsgi.py settings.apps.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', 'app2' ] settings.celery_config.py BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Project.__init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) celery.py from __future__ import absolute_import, unicode_literals from .settings import celery_settings from celery import Celery import os # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.celery_settings") app = Celery('eiu') # # Using a string here means the worker doesn't have to serialize # # the configuration object to child processes. # # - namespace='CELERY' means all celery-related configuration keys # # should have a … -
Nginx reverse proxying to Django receiving `upstream prematurely closed connection while reading response header from upstream`
At the risk of infuriating the community I'm not going to include any config as, while I'm sure it's relevant, I'm trying to understand the theory behind this phenomenon. Some teammates and I maintain a webserver for internal use. In the/our world of internal tools things are never productized. We typically are doing whatever is necessary to deliver some value to our co-workers. Stakes and available resources are low. As such we've committed a cardinal sin in standing up a Python 2 Django server on its own. No WSGI middleware, no additional processes. I've seen the admonitions but we've done what we've done. I recently stood up an Nginx instance in front of this abomination to give us the ability to "hot-swap" instances of our web application with zero downtime. I still did not insert anything in between. Nginx is simply reverse-proxying, over localhost http to the Django instance listening on a localhost non-standard port. After this change we started seeing bursts of 502s from Nginx. There are a few pages that are "live" in that they do some polling to check for updates to things. As such, there is "a lot" of traffic for the number of users we … -
django signals not working on usercreation
I created a signals supposed to create a profile for each created users in my signals.py file but it's not working. i've tried to check if there's an error with the command "python manage.py check" but that seems not to work as well... i've been on this for a whole 3hours..please help a friend. models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f"{self.user.username}'s profile " signals.py from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, created, instance, **kwargs): if created: Profle.instance.create(user=instance) @receiver(post_save, sender=User) def create_profile(sender, instance, **kwargs): instance.profile.save() apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals what am i doing wrong -
I cannot import a function within the same file in Django
{% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/calcu.css' %}"> </head> <form id="calci_form" method="get" action="operation"> <label class="l1">Number 1</label><input type="text" name="num1" class="tb1" value="{{fvalue}}"> <label class="l2">Number 2</label><input type="text" name="num2" class="tb2" value="{{svalue}}"> <label class="l3">Result</label><input type="text" class="tb3" name="user_input" value={{result}}> <input type="submit" name="sym" class="btn1" value="Calculate"> </form> </html> the above is my html page in Django - calculate.html I am new to django and I am just trying to add a function to print the sum of two numbers. the function is in add.py - def add(a,b): return a + b The function I am calling this from is in views.py - from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from add import add # Create your views here. def home(request): return render(request, "calculate.html") def operation(request): if 'sym' in request.GET: first = int(request.GET['num1']) second = int(request.GET['num2']) res = add(first,second) context = { 'fvalue': first, 'svalue': second, 'result': res, } return render(request,'calculate.html', context) now the add.py is in the same folder as views.py. However it says "The site can't be reached" Don't know what to do. -
Django PasswordChangeView throws "The password is too similar to the email address." error
I trying to create URL where users can change their passwords. This error is kinda weird, because I don't even have field for email in my registration form. In my registration form I asked user only for username and password. Also, I don't change standart User model. If someone need any code parts to help me, write what do you need. I don't even know what should I attach because have no idea what is going wrong.