Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
django-storages S3boto3 upload status
I'm using django-storages to upload several files using a Model with a FileField in Django Rest Framework. Everything works fine, the frontend aplication just waits until the upload finish and the promise is resolved i the fron while in the backend a database registry is save in the database. But when the files are too large or there is network issues, the promise just time out and the upload sometimes is done and sometimes is not, and sometimes it uploads the file without loading the link to the database. Is there any way to generate a progress indicator that shows me the upload status, I could request for the status with my frontend aplication, with a recursive request instead of a Promise that is timed out. Is there is any other sugestion i am open to hear one. -
Heroku versus AWS
I am trying to deploy a personal website (python django based framework) which contains text and few images. Can someone tell if their are any advantages and disadvantages of deploying to heroku versus AWS. PS: I have deployed it on AWS but the images are not loading. So I am considering Heroku but not sure if I should use Heroku or AWS would be more stable. -
How can I print this Django raw SQL query? Preferably to a table
I have been working on a Django app to help us clean up some old Tableau workbooks. It gives users a front end web ui to decide which books to keep and which to delete. I'm going to be handling a lot of this by way of SQL and Django. Here is the SQL query I have written: from django.db import connection username = str("lastname, firstname") def dictfetchall(cursor): # Returns all rows from a cursor as a dict desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def query(): cursor = connection.cursor() cursor.execute("SELECT Owner_Name,Owner_Email,Id,Name FROM tableau_books WHERE Owner_Name = %s", (username,)) results = dictfetchall(cursor) for item in results: print(item) Right now, this function just queries the fields I want and prints them in a legible way. Here is my view where I'm calling it: def dashboard(request): if request.method == 'POST' and 'run_script' in request.POST: # import function to run from main_app.queries import query # call function query() return render(request, 'dashboard.html') Lastly, here is my button I'm using to actually run the code in html: <form method="post"> {% csrf_token %} <button type="submit" name="run_script">Find Workbooks</button> </form> Is there an easy way to, instead of printing … -
How to increase quantity for each multiple items with the same slug url
How does one increases the quantity for each multiple item with the same slug url? When i added two items with the same slug url to cart, then i try to increase the quantity it only increases the first item in cart and not the second item. enter image description here Models.py class Item(models.Model): title = models.CharField(max_length=250) image = models.ImageField(null=True) price = models.IntegerField() old_price = models.IntegerField(null=True, blank=True) description = HTMLField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField(max_length=250, unique=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) class Meta: ordering = ['-timestamp'] db_table = 'items' verbose_name_plural = 'Items' def __str__(self): return self.title class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) def __str__(self): return f"{self.quantity} of {self.item.title}" Views.py def update_cart(request, pk, slug): item = get_object_or_404(Item, pk=pk) print(item) if request.method == 'POST': pk = request.POST.get('pk', None) #retrieve id qty = request.POST.get('quantity', None) order_item_qs= OrderItem.objects.filter( item=item, user=request.user, ordered=False ) if order_item_qs.exists(): item = order_item_qs.first() item.quantity = qty item.save() return redirect("shop:order-summary") Urls.py path('update-cart/<int:pk>-<slug:slug>/', update_cart, name='update-cart'), Order-sumarry template: <form method="POST" action="{{ order_item.item.get_update_cart_url }}"> {% csrf_token %} <p> <input type="button" value="-" class="minus"> <input type="number" value="{{ order_item.quantity }}" name="quantity" id="qty1" class="quantity_class" min="1" required> <input type="button" … -
unique_together in a model.Models vs uniquetogethervalidator of serializers
If i have a model A with (field1 and field2 are fields of model) `unique_together = ('field1', 'field2')` in Meta class and a serializer which is a model serializer on model A, then why should I or why should not I use Uniquetogethervalidator in Meta of serializer. Why we need this validator if we already have condition in Model? Or what is difference between using a unique_constraint in model and uniquetogethervalidator in serializer ? -
for loop with an integer in django's templates tags
In my Django template {{review.stars}} is an integer from 1 to 5, but instead of showing a simple number I want to show a number of star icons equal to the {{review.stars}} integer. I should write something like: for n in range(1, review.stars+1): add star icon but obviously I can't write something like that in Django template tags. What's the pythonic way to run a loop a variable number of times? -
Django dynamically add fields without creating new model instances
I'm attempting to create a form that allows someone to enter multiple phone numbers. I'd like to make it possible to click a button to add an additional field to the form but I am not quite sure how to do that. I looked at FormSets but I don't want to create a new model instance every time someone adds a new phone number. Thanks in advance -
django-objects tag filter
I'm calling a post.objects.all object on my html page. on the same page last-post. I made a filter for this but I get an error. calling the last 3 posts I want to do I can't type .objects.order_by () because it's probably an object. views.py : posts=post.objects.all() context = { 'posts': posts, 'category':category, } return render(request, "post/post-list.html", context) html: {%for post in posts|lasted %} filter.py @register.filter def lasted(post): return post.objects.order_by('post_date')[:3] AttributeError at /post/index/ 'Page' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/post/index/ Django Version: 2.2.7 Exception Type: AttributeError Exception Value: 'Page' object has no attribute 'objects' Exception Location: C:\Users\Barbaros\Desktop\All\env\lib\site-packages\django\template\defaultfilters.py in lasted, line 73 Python Executable: C:\Users\Barbaros\Desktop\All\env\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Barbaros\\Desktop\\All', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\Scripts\\python37.zip', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\DLLs', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\lib', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\Scripts', 'c:\\users\\barbaros\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\barbaros\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\Users\\Barbaros\\Desktop\\All\\env', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\lib\\site-packages'] Server time: Fri, 22 Nov 2019 20:36:41 +0000