Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Redis - What counts as a connection? Why does my connection limit not drop to zero, after Python Celery completes task?
I am using the Heroku Redis add-on for my Django application, as the broker for my Python Celery background tasks. The Celery background task is successfully completed using Heroku Redis as the broker. However within the Heroku Redis add-on dashboard (data.heroku.com/datastores/) it still says there are 8 clients (connections). 1) Why is that, I thought it would be 0 clients (connections) since the celery background task is completed. 2)In the Heroku Redis dashboard the number of clients so far has varied between 13 and 8 clients. Why so many clients? I am only running a single python celery background task at a time, so thought it would always say 1 client. -
How to save an instance and update a reverse M2M field in a modelForm
I have two models with an M2M relationship: class Author(models.Model): name = models.CharField() class Publisher(models.Model): authors = models.ManyToManyField(Author) When creating a new Author, I want to be able to set Publishers for that Author. Currently I handle this in the form: class AuthorForm(forms.ModelForm): publishers = forms.ModelMultipleChoiceField(queryset=Publisher.objects.all()) def __init__(self, *args, **kwargs): super(AuthorForm, self).__init__(*args, **kwargs) # If the form is used in a UpdateView, set the initial values if self.instance.id: self.fields['publishers'].initial = self.instance.publisher_set.all( ).values_list('id', flat=True) def save(self, *args, **kwargs): instance = super(AuthorForm, self).save(*args, **kwargs) # Update the M2M relationship instance.issuer_set.set(self.cleaned_data['issuers']) return instance class Meta: model = Author fields = ['name', 'publishers'] This works fine when updating an existing Author. However, when I use it to create a new one I get: <Author: Sample Author> needs to have a value for field "id" before this many-to-many relationship can be used. I understand this is because the instance needs to be saved first, however in def save() I am doing this (instance = super(AuthorForm, self).save(*args, **kwargs)). Where am I going wrong? -
How to set cache control headers in a Django view class (no-cache)
Now this took me some time to figure out, so I will self-answer it. I wanted to disable browser caching for one specific page in Django on a View. There is some information how to do this if the view is a function, but not if it's a class. I did not want to use a middleware, because there was only one specific view that I didn't want to be cached. -
passing token as headers from an html file using js
i have added an input field which takes token as input and fetches a page with authenctication required and sends that token as header but this doesnt seem to work..all i want to do is take token as input from frontend page and give access to pages instead 0f using POSTMAN <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form> <input type="text" id="token" placeholder="token"> <button type="button" onclick="myFun()"> submit</button> </form> </body> <script> function myFun() { var token = document.getElementById("token").value; object = { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token } } fetch('http://127.0.0.1:8000/app/task-list/', object) </script> </html> -
run an os.system command via Django on Raspberry pi
Hello i have set up a django website on my raspberry pi running with apache2 i want to controll some wireless sockets via 433mhz and the 433Utils/RPi_utils Library. I've installed the Library inside my virtualenv. my views.py looks like this: from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect import os def light(response): return render(response,"light/light.html", {}) def one_on(request): os.system("/home/pi/Dev/cfehome/src/light/433Utils/RPi_utils/codesend 1381717") return render(request, "light/one_on.html") If i open http://.../light/one_on.html in my browser the page loads and everything is there but the pi sends nothing to the wireless socket Could you please helb me? -
Django not creating user after extending AbstractUser
I tried extending my AbstractUser to allow more user types and to also allow users to create an account using their email address. However, I have been facing issues with user creation form on the frontend despite the fact that my Django admin works perfectly as I can create or sign in using email address instead of a username. In addition, I noticed that anytime I submit the account creation form, the values auto-populate my browser's address bar, and of course, the user won't be created. I don't know if I can get some help to this issue, maybe I am simply missing a very vital step. Below is a sample of auto-populated values shown in my browser's address bar when I (users) submit the form http://127.0.0.1:8000/signup/company/?csrfmiddlewaretoken=7AC4rKoyFsYTkcOKLpaiREAYZQwu1i3hGlF51I3Svs65Kf4Fkc64j25YZAN2pKE4&email=jyak%40yahoo.com&password1=oluwasegun01&password2=oluwasegun01&name=Hedge&number_of_employees=20&country=1&phone=012345678901 Below are my codes: Models.py from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin, AbstractUser from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from accounts.managers import CustomUserManager from accounts.validators import validate_digit_length from data.models import Country class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) #some other user types username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, … -
Django migration strategy for changing ForeignKey to IntegerField without losing data
I have model class SomeModel(models.Model): target_field = models.ForeignKey( 'OtherModel', on_delete=models.PROTECT, verbose_name=_('Target Field'), ) And i want to change it to class SomeModel(models.Model): target_field_id = models.PositiveIntegerField(_('Target field id')) I want to do it without losing data stored in target_field_id by ForeignKey field. I tried just to run makemigrations. But it deletes column and then creates new. Much appreciate any help. -
When migrating: Encoding "UTF8" has no equivalent in encoding "LATIN1"
Django 3.0.6 PostgreSQL 12.3 At my localhost everything is Ok. But when I try to deploy to my production server: (venv) root@tmpgmv:~/pcask/pcask# python manage.py migrate Operations to perform: Apply all migrations: admin, applications, auth, author, category, code_sample, contenttypes, general, hyper_link, image, languages, marketing, people, polls, post, quotations, sessions, sidebar, taggit, videos Running migrations: No migrations to apply. Traceback (most recent call last): File "/root/pcask/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UntranslatableCharacter: character with byte sequence 0xd0 0xa0 in encoding "UTF8" has no equivalent in encoding "LATIN1" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 256, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/root/pcask/venv/lib/python3.6/site-packages/django/core/management/sql.py", line 50, in emit_post_migrate_signal **kwargs File "/root/pcask/venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/root/pcask/venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/root/pcask/venv/lib/python3.6/site-packages/django/contrib/auth/management/__init__.py", line … -
How to transfer a html table from a template to a database table
I have an HTML template (index.html) which gets populated dynamically with an HTML table. The table data can be changed by the user. After the user has made his changes, he then can save the whole table data to a Django database table by clicking a submit button. -
How do I automatically delete images in Django media file when I delete the objects in Admin?
please help! I am using Django 3 and have a basic blog with a title, description and image for each entry. In Django admin I can delete each blog post however, when I look in my media file in Atom all the images are still there and I have to manually delete them... how do I get them to auto delete when I delete them in Admin? Model.py from django.db import models class Blog(models.Model): title = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to='images/', default='images/road.jpg') last_modified = models.DateField(auto_now=True) Views.py from django.shortcuts import render from .models import Blog def home (request): blogs = Blog.objects.all() return render (request,'blog/home.html', {'blogs':blogs}) -
Run Django manage.py shell commands on elastic beanstalk
I have my Django service up and running on AWS elasticbeanstalk. eb deploy works perfectly. But I would like to run some functions from shell of Django on by eb or maybe perform migrations on my DB. I am unable to find my package after I eb ssh so cant find the manage.py file. Related question - Run manage.py from AWS EB Linux instance I believe it might be outdated ? -
How to implement foreign key relationships with django-import-export
I've made a django app in which I want to import data from .xlsx files to models with django-import-export module. My models.py is: class File(models.Model): name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Data(models.Model): file = models.ForeignKey(File, on_delete=models.CASCADE, null=False) url = models.URLField() I want that when I import .xlsx file its contents go into Data model and its File name into File model with foreign key relationship between them. My admin.py file is: from import_export.admin import ImportExportModelAdmin from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from django.contrib import admin from .models import File, Data admin.site.register(File) class DataResource(resources.ModelResource): file = fields.Field( widget=ForeignKeyWidget(File, 'name')) class Meta: model = Data exclude = ('file',) @admin.register(Data) class DataAdmin(ImportExportModelAdmin): pass I tried everything in the module's documentation. But I can't solve the issue I'm facing -
Dealing with unique constraints in nested serializers
In my Django project, I made a custom Auth model with unique email and username, I made a different model where I defined the user field and connect it with ForignField, and also made serializer for this model, but whenever I adding 2nd object in the model it shows me validation error like { "error": { "user": { "username": [ "user with this username already exists." ], "email": [ "user with this email already exists." ] } } } I got one article on how to dealing with unique constraints in nested serializers link of that article but this article only shows me how to tackle username which is working fine but I also want to validate email Id. How can I write a custom validator in serializer which will deal with both fields? -
In Django class based views how I do I use multiple slugs with slug_url_kwarg
According to the documentation, The name of the URLConf keyword argument that contains the slug. By default, slug_url_kwarg is 'slug'. How do I use this for an UpdateView where I have two slugs book_slug and chapter_slug? According to this answer, I can override get_queryset method. But is there a way to use multiple slugs with slug_url_kwarg? I tried slug_url_kwarg = ['book_slug', 'chapter_slug'] but it doesn't work. -
Why are integration tests failing on updates to model objects when the function is run on Django q-cluster?
I am running some django integration tests of code that passes some functions to Django-Q for processing. This code essentially updates some fields on a model object. The app uses signals.py to listen for a post_save change of the status field of the Foo object. Assuming it's not a newly created object and it has the correct status, the Foo.prepare_foo() function is called. This is handled by services.py which hands it off to q-cluster. Assuming this executes without error hooks.py changes the status field of Foo to prepared, or keeps it at draft if it fails. If it passes then it also sets prepared to True. (I know this sounds convoluted and with overlapping variables - part of the desire to get tests running is to be able to refactor). The code runs correctly in all environments, but when I try to run tests to assert that the fields have been updated, they fail. (If I tweak the code to bypass the cluster and have the functions run in-memory then the tests pass.) Given this, I'm assuming the issue lies in how I've written the tests, but I cannot diagnose the issue. tests_prepare_foo.py import time from django.test import TestCase, override_settings, … -
Django reproduce concurrency example with select_for_update()
I'm reading over this article on handling concurrency in django The post talk about the following example: User A fetches the account — balance is 100$. User B fetches the account — balance is 100$. User B withdraws 30$ — balance is updated to 100$ — 30$ = 70$. User A deposits 50$ — balance is updated to 100$ + 50$ = 150$. I tried to reproduce with a UserBalance model with balance column that use IntegerField() def test_con(id): with transaction.atomic(): user_balance = UserBalance.objects.select_for_update().get(pk=int(id)) sleep(60) user_balance.balance -= 30 user_balance.save() So this transaction is lock for 60 seconds In the first shell i go into manage.py shell to call it In another shell after i execute test_con(5) i ran the following : >>> from backend.models import UserBalance >>> user_balance = UserBalance.objects.get(pk=5) >>> user_balance.balance += 50 >>> user_balance.save() >>> print(str(user_balance.balance)) the second shell wait till the first shell test_con(5) transaction is completed(as expected) and return the balance but it return 150 ? shouldn't it be 120 ? I'm confused about why this locking mechanic doesn't work -
How to retrieve post data from view of django app
Hi All I am new to jquery and django. I used the following code to post when the button with id 'submit_data' is clicked. Is it possible to retrieve the dictionary { data_key: 'myString'} from the views.py of django app? If yes how? $(function() { $('#submit_data').on('click',function() { $.post('/url/', { data_key: 'myString'}, function(result) { alert('successfully posted'); }); }); }); -
Django 3.0+ : django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
so i have been googling for a solution in the past 5 hours, maybe more? I did all the solutions that are listed like checking each installed_app and adding django_setup() then knowing that django_setup() should NOT be used. Ill edit what you need to see, because im not sure where exactly my error is. ive trued python manage.py runserver/check and thats what i get: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_li ne utility.execute() File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\saraa\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\contrib\auth\apps.py", line 8, in <module> from .checks import check_models_permissions, check_user_model File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\contrib\auth\checks.py", line 8, in <module> from myapi.models import is_anonymous File "C:\Users\saraa\PycharmProjects\okobackend\myapi\models.py", line 3, … -
How to rename is_active in user table in django?
This is my user model: class User(AbstractUser): id = models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True ) email = models.EmailField(_("email address"), max_length=255, unique=True) avatar = models.CharField(_("avatar"), max_length=128, default="") username = None EMAIL_FIELD = "email" USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email Now, I need to rename is_active to active. I originally wanted to cancel is_active like username, and then create a new active field is_active = None active = models.BooleanField(_("active"), default=False) This does not seem to work, and I received an error message (admin.E116) The value of 'list_filter[2]' refers to 'is_active', which does not refer to a Field. -
Why request.body is empty on call custom API using tastypie?
Facing issue with POST API call. I am using tastypie prepend_urls wrap_view for login custom api. I am using below versions: Tastypie 0.14.3 Tastypie_swagger 0.1.4 Django 2.2.12 Python 3.5.2 I am using below deserialize method to abstract data from payload. I don't know why I'm getting empty request.body. request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json') ) If I'm trying to convert request data into json, Then it is raising Request is not valid JSON. As per my debugging it is using package method named deserialize and into serialize.py of tastypie. It is using from_json method. Also request.body returning blank query dict. I am receiving data which is passing into POST call with request.GET. Is it happening due to upgraded version of python and tastypie? Is there something am I doing wrong? Here is some output of my request. It would be helpful to understand the scenario. I am getting this params into GET instead of request.body. request.GET <QueryDict: {'username': ['abc@gmail.com'], 'password': ['123456']}> Empty POST QueryDict request.POST <QueryDict: {}> Request call: request <WSGIRequest: POST '/api/v1/user/login/?username=abc%40gmail.com&password=123456'> self.method_check(request, allowed=['post']) 'post' request.body b'' It should have JSON payload like {"username":"password"}. Please suggest me what should I do for resolved below error. { "status": "0", "message": "Request is … -
How do I create Groups for custom users in Django?
I created a Custom User Model by basically copying and pasting the full example given in the Django Docs. But in the docs, they unregistered groups. But in my project I will need groups because I'll have different uper types. So how can I still have groups and add my custom users to them? -
Set environment variables uwsgi
I'm working with a Django project and want to deploy it using nginx with uwsgi. I have to set these environment variables for my app to work (I'm using Gurobi if people are interested). export GUROBI_HOME="/opt/gurobi902/linux64" export PATH="${PATH}:${GUROBI_HOME}/bin" export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${GUROBI_HOME}/lib" My app works fine in my development environment, but when I try deploying it to my server, I get a Gurobi import error, which means these environment variables are not properly set up in my uwsgi environment. I've tried setting up these environment variables in 2 ways in my uwsgi configuration file, but none works. [uwsgi] ... env = GUROBI_HOME="/opt/gurobi902/linux64" env = PATH="${PATH}:${GUROBI_HOME}/bin" env = LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${GUROBI_HOME}/lib" The other way I tried was taken from this answer. [uwsgi] ... route-run = addvar:GUROBI_HOME="/opt/gurobi902/linux64" route-run = addvar:PATH="${PATH}:${GUROBI_HOME}/bin" route-run = addvar:LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${GUROBI_HOME}/lib" Does anyone know how to properly pass environment variables to uwsgi? Thanks all. -
How to Count distinct rows over two ManyToMany Fields
from django.db import models class Group(models.Model): users = models.ManyToMany(User, blank=True, related_name="groups" class Task(models.Model): users = models.ManyToManyField(User, blank=True, related_name="personal_tasks") groups = models.ManyToManyField(Group, blank=True, related_name="group_tasks") Note: Code above is to demonstrate the concept, it is not code that is being used. So using the models above as an example, would it be possible (with a single query preferably) to get a total count of unique users? I initially thought of just adding the counts of the users field and the groups__users field, however, I would like to account for the possibility that someone was both assigned the task personally, and through their group. -
Why Django does not generate app name into href paths?
I hope someone could maybe help me, please : I am quite new to Django and currently trying to implement a simple login/logout for a test page. However, for some reasons, the Django does not generate the name of application in the href (so where it should be xxxx/main/register, it is only xxx/register). But when I put the app name manually in the href in Pycharm, it generates it two times (so it becomes xxx/main/main/register). So for this: <a href="/logout/">Logout</a> I got this url: http://127.0.0.1:8000/logout/ If I write this: <a href="main/logout/">Logout</a> I got this url: http://127.0.0.1:8000/main/main/logout/ But I need to get this: http://127.0.0.1:8000/main/logout/ It worked before, but from one minute to another, it suddenly stopped directing to the good path. And django does the same thing with every links in my site. main/urls.py: from django.urls import path from . import views app_name = 'main' # here for namespacing of urls. urlpatterns = [ path("", views.homepage, name="homepage"), path("register/", views.register, name="register" ), path("logout/", views.logout_request, name="logout"), ] main/views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Tutorial from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import logout, authenticate, login from django.contrib import messages def homepage(request): return render(request = request, template_name='main/home.html', … -
How to get and show many images in the Django application from Flask programs that live on other servers through a GET request for them
I have the Django application (D) as a dashboard site on some instance of AWS and several Flask working applications (F) on others. I need to show many images (such as .png scenes) in the D web interface. To do this, I need to get files from F, where they are stored using a GET query with a path file to the current instance. The model cannot be used via AWS S3 to perform this specific task. I'm thinking about the built-in Python socket, but I don't see a solution ... Maybe someone has faced the same problem and can say a solution, which way can I use? Thanks.