Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't change Django admin login URL
I will change django login panel URL. I change admin url in urls.py file. URL changed but i can't login. general urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('testadminlogin/', admin.site.urls), ] in settings.py: ... LOGIN_URL = '/testadminlogin/' LOGIN_REDIRECT_URL ='/testadminlogin/' ... I will login by this URL: "mysite.com/testadminlogin/" -
Deployment Failed with Error: Package deployment using ZIP Deploy failed
I am trying to deploy a django project in azure from GitHub repository but I am getting error during the deployment. I am getting this error: Failed to deploy web package to App Service. 2022-01-02T15:32:52.2053869Z ##[error]Deployment Failed with Error: Package deployment using ZIP Deploy failed. Refer logs for more details. How can I resolve it? 2022-01-02T15:07:42.4101966Z with: 2022-01-02T15:07:42.4102399Z app-name: stockprojection 2022-01-02T15:07:42.4102889Z slot-name: Production 2022-01-02T15:07:42.4115035Z publish-profile: *** 2022-01-02T15:07:42.4115476Z package: . 2022-01-02T15:07:42.4116058Z ##[endgroup] 2022-01-02T15:07:43.9633760Z Package deployment using ZIP Deploy initiated. 2022-01-02T15:32:51.1581899Z Updating submodules. 2022-01-02T15:32:51.1583435Z Preparing deployment for commit id 'f47d703f2a'. 2022-01-02T15:32:51.1584587Z Repository path is /tmp/zipdeploy/extracted 2022-01-02T15:32:51.1585520Z Running oryx build... 2022-01-02T15:32:52.1954843Z Command: oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform python --platform-version 3.9 -i /tmp/8d9ce01a48e2911 --compress-destination-dir -p virtualenv_name=antenv --log-file /tmp/build-debug.log 2022-01-02T15:32:52.1957351Z Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx 2022-01-02T15:32:52.1958337Z You can report issues at https://github.com/Microsoft/Oryx/issues 2022-01-02T15:32:52.1992563Z 2022-01-02T15:32:52.1993572Z Oryx Version: 0.2.20210826.1, Commit: f8651349d0c78259bb199593b526450568c2f94a, ReleaseTagName: 20210826.1 2022-01-02T15:32:52.1994721Z 2022-01-02T15:32:52.1995241Z Build Operation ID: |da22zDrMO/Q=.cac2beba_ 2022-01-02T15:32:52.1996043Z Repository Commit : f47d703f2a594452a83ae4301b5d6ce8 2022-01-02T15:32:52.1996497Z 2022-01-02T15:32:52.1997051Z Detecting platforms... 2022-01-02T15:32:52.1997609Z Detected following platforms: 2022-01-02T15:32:52.1998100Z python: 3.9.7 2022-01-02T15:32:52.1999279Z Version '3.9.7' of platform 'python' is not installed. Generating script to install it... 2022-01-02T15:32:52.1999807Z 2022-01-02T15:32:52.2000549Z Using intermediate directory '/tmp/8d9ce01a48e2911'. 2022-01-02T15:32:52.2001012Z 2022-01-02T15:32:52.2001533Z Copying files to the intermediate directory... 2022-01-02T15:32:52.2002087Z Done in 0 sec(s). 2022-01-02T15:32:52.2002345Z 2022-01-02T15:32:52.2002782Z Source directory : /tmp/8d9ce01a48e2911 2022-01-02T15:32:52.2003367Z … -
Django - Get highest value from each user
I have this models: Models: class User(models.Model): name = models.CharField(max_length=255, null=True, blank=True, verbose_name='Name') class Grad(models.Model): grad = models.CharField(max_length=255, null=True, blank=True, verbose_name='Grad') order = models.PositiveIntegerField(max_length=255, null=True, blank=True, verbose_name='Order') class Number(models.Model): user = models.ForeignKey(User, null=True, blank=True, verbose_name='User', on_delete=models.CASCADE) grad = models.ForeignKey(Grad, null=True, blank=True, verbose_name='Grad', on_delete=models.CASCADE) View: user_numbers = Number.objects.all() Get example: But i want only get the highest order grad value to each user: Thank you in advance! -
Django Rest Framework give me validation error that shouldn't be raised when using Unit Tests
I am creating this API and in determined point of my tests (contract creation endpoint) I am receiving an invalid error. The error says that I am not passing some required attribute to the API when creating a contract, but I am. The weirdest thing is that when I tried to create from the Web browser by hand, the issue wasn't raised and the contract was created I am puting here a lot of codes just for replication purposes, but the code that is really important to see it is the ContractSerializer and the test_contract_creation function Here is my code: models.py from django.core.exceptions import ValidationError from django.db import models from django.core.validators import ( MaxValueValidator, MinValueValidator, RegexValidator, ) from core.validators import GreaterThanValidator, luhn_validator class Planet(models.Model): name = models.CharField( max_length=50, unique=True, null=False, blank=False ) def __str__(self) -> str: return self.name class Route(models.Model): origin_planet = models.ForeignKey( Planet, on_delete=models.CASCADE, related_name="origin", ) destination_planet = models.ForeignKey( Planet, on_delete=models.CASCADE, related_name="destination", ) fuel_cost = models.IntegerField(validators=[GreaterThanValidator(0)]) class Meta: unique_together = (("origin_planet", "destination_planet"),) def clean(self) -> None: # super().full_clean() if self.origin_planet == self.destination_planet: raise ValidationError( "Origin and destination planets must be different." ) def save(self, *args, **kwargs): self.full_clean() super().save(*args, **kwargs) def __str__(self) -> str: return f"{self.origin_planet} - {self.destination_planet}" class Ship(models.Model): … -
Managing django secrets
I am creating a Django web application that will be hosted in AWS. I'm developing on my laptop (Mac) and using docker compose to run a postgres database in AWS as well. Accordingly, sometimes I am using a development database from my Mac in PyCharm, and other times I need to compile and run the docker to test that the functionality works in the container. The challenge I am facing is the management of secrets across all of these locations. It would be ideal to have one "secret vault" which could be accessed at run-time from either within the docker or within PyCharm to keep life simpler. I am familiar with .env files and the manner by which these can be imported, but this also requires me to copy them into the docker container at build time. Is there some "simple yet robust" way to manage this more easily? It feels like having copies of different .env files in different environments presents its own risks. -
SL connection has been closed unexpectedly server closed the connection unexpectedly This probably means the server terminated abnormally
i want run python manage.py runserver but got this error !! django.db.utils.OperationalError: connection to server at "172.16.11.139", port 5432 failed: FATAL: password authentication failed for user "some_name" connection to server at "172.16.10.139", port 5432 failed: FATAL: password authentication failed for user "some_name" i use this article for postgres remote connection https://www.bigbinary.com/blog/configure-postgresql-to-allow-remote-connection what i miss?! setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('NAME'), 'USER': os.getenv('USER'), 'PASSWORD': os.getenv('PASSWORD'), 'HOST': os.getenv('HOST'), 'PORT': int(os.getenv('PORT')), } } -
Django manage.py runserver command not working
image I am using Python 3.10 and Django version 4.0. When I try to run manage.py runserver, the terminal doesn't give me localhost address. I tried restarting my pc, but still not working. Please help me. -
Django ModelForm never passes is_valid()
I'm new to Django and I am currently trying to store data entered from a form into a model/database. The bit which I think is causing the issue is that I don't want all the model fields accessible on the form. The model I have has the fields as follows: description = models.TextField() date_referred = models.DateTimeField(default=timezone.now) full_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone_number = models.CharField(max_length=17, blank=True) column_number = models.IntegerField() notes = models.TextField() colour = models.CharField(max_length=6) user = models.ForeignKey(User, on_delete=models.CASCADE) The ModelForm I am using is as follows: class ReferralForm(ModelForm): class Meta: model = kanban_item fields = ["item_name", "description", "full_name", "email", "phone_number"] The code inside of the views.py file is this: def submit_referrals(request): form = ReferralForm() if request.method == "POST": form = ReferralForm() print(request.POST) if form.is_valid(): print("VALID") referral = form.save(commit=False) referral.user = request.user referral.column_number = 0 referral.colour = "ffffff" referral.save() else : print ("NOT VALID") As you can see, I am trying to create a model from the form then add the extra fields and then save the model to the database. This is not working as whenever I submit the form my code never gets past the is_valid method on the form. Any suggestions or answers are appreciated as I … -
How to count objects from m2m connection
i have a problem with understanding of how to count objects from m2m connection in django. I need to get number of photos in photoalbum. Here is my model of album: class PhotoAlbum(models.Model): title = models.CharField(verbose_name='Название альбома', max_length=50, null=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='Автор') created_at = models.DateTimeField(verbose_name='Дата создания', editable=False, default=datetime.datetime.today()) photos = models.ManyToManyField('Photo', verbose_name='Фото', blank=True, related_name='photo_albums') number_of_photos = "something" How can i get number of connected with album photos for each photo album? -
Uncaught ReferenceError: Cannot access 'chatSocket' before initialization at HTMLImageElement.document.getElementById.onclick
I am doing a chatting app with djnago I am using channels_redis, it works perfectly in localhost when I was using channels but once I changed to channels_redis and used heroku redis addons and aws recently and deployed to heroku I get this error message Uncaught ReferenceError: Cannot access 'chatSocket' before initialization at HTMLImageElement.document.getElementById.onclick I really don't how can I solve this problem ....because now whenever I click on the send message button I get this error , let me show you first the js part in my chat template.html <script> /* send message*/ document.getElementById('send-btn-id').onclick = function (e) { const msg = document.getElementById('message').value; chatSocket.send(JSON.stringify({ 'message': msg, 'user': me, 'friend': friendName })); document.getElementById('message').value = ""; $("#card-body").animate({ scrollTop: 20000000 }, "slow"); }; const friendName = JSON.parse(document.getElementById('friend').textContent); const me = JSON.parse(document.getElementById('me').textContent); /* set friend profile name */ document.getElementById('friend-name').innerHTML = friendName['username']; /* start conversation */ document.querySelector('.start-conversation').innerHTML = 'Start conversation with <strong>'+friendName['username']+'</strong>'; /* connection request */ const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + friendName['username'] + '/' ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); var class_name = 'in'; var profile_image = '{{friend_obj.profile.image.url}}'; if(me['username'] == data.user['username']) { data.user['username'] = 'Me'; class_name = 'out'; profile_image = '{{request.user.profile.image.url}}'; } var chat_list = … -
Django filter data while signup according to country
I'm making a project using Django and PostgreSQL. the user have to signup and after that login. Problem While user is signing up I'm asking different questions like name, email etc one field is **Country(home country)**. once the data store in database. now if the user want to login I want the he/she can see all the data related to home country. e.g UK people can't see data from US or any other country and vise versa. -
I am working on django project when i run >> python manage.py sqlmigrate travello 0001 command it show the following error help on this
enter image description here python manage makemigrations python manage.py sqlmigrate travello 0001 please find the image and provide the solutions -
I've deleted my .sock file - Django, Nginx, Gunicorn
When I was trying to pull from Git, I accidentally deleted the sock file. What am I supposed to do now? My websites showing "502 Bad Gateway" and nothing's working. I need help, fast. Could you tell me what to do now? -
django migrations and git branches while working on multiple features simultaneously
In django, when working on multiple new features simultaneously, what is the best way to handle migrations with git? I’m in middle of working on feature1, on its own branch. Now I need to create feature2 and push it to production. Should I: fork new feature2 branch off of production, create feature2, merge back to prod, migrate. fork new feature2 branch off of production, create feature2, migrate, merge back to prod. Or some other way? And when I go back to feature1, what do i do to insure everything will be up to date? -
Django ORM: Excluding Specific Record in Many-to-Many Relationship
I have a many-to-many relationship between two models Profile and Conversation like this: class Profile(models.Model): # ... class Conversation(models.Model): members = models.ManyToManyField(Profile, related_name="conversations") Now I want to select all the conversations that a specific profile is a member in it, I tried this which worked but I'm not sure if it's the right way: conversations = Conversation.objects.filter(members='<profile_pk>') Also, I want to exclude that member's data from the result because I already have it, or should I exclude his data on the client side? -
I'm trying host Django prj with xampp
I have set up all the necessary steps such as installing mod_wsgi (including copying to apache's modules folder), c++ tool build, but when I run xampp, it fails.1 and what's keeping it from running is this line of code LoadModule wsgi_module modules/mod_wsgi.so located in the file httpd.conf -
Django not showing images in admin's editor (404 error)
I'm try create post and add to this post images. And i'm use for this Django-summernote in Django 3.0. Picture upload to folder on hard disk, but not showing in editor. Console show 404 Error. Please, give me advice how to fix it? Thank you! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/filebrowser/', site.urls), path('summernote/', include('django_summernote.urls')), path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to="", blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return "/api/article/%i/" % self.id def __str__(self): return self.title Console screenshoot -
how to fix typeError: sequence item 1: expected a bytes-like object, str found
i'm trying to create an object in database with django. my configuration is below. 'nucoin' : { 'ENGINE': 'mysql.connector.django', 'NAME': "db_name", 'USER': 'db_user', 'PASSWORD': 'db_password', 'HOST': 'db_host', 'PORT': '3306', 'SSL': True, }, and i'm getting the following trackback.. Original exception was: Traceback (most recent call last): File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/rest_framework/serializers.py", line 939, in create instance = ModelClass._default_manager.create(**validated_data) File "/home/ahmed/bitbucket/notification_platform_sdk/backend/projects/managers.py", line 23, in create project.save(using="nucoin") File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1410, in execute_sql cursor.execute(sql, params) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/mysql/connector/django/base.py", line 149, in execute return self.cursor.execute(query, new_args) File "/home/ahmed/gitclones/clone-beru/web_push/backend/envNotifer/lib/python3.8/site-packages/mysql/connector/cursor_cext.py", line 263, in execute stmt = RE_PY_PARAM.sub(psub, stmt) TypeError: sequence item 1: expected a bytes-like object, str found if you need more detail. … -
UserProfileInfo matching query does not exist Django
I need to have extra information about a person, more than the default User model provides. That's why I've created the UserProfileInfo model that's supposed to hold all this extra info, such as house_number, phone_number, full_name, and community. Now, an instance of UserProfileInfo is created whenever a user registers. But when I run this route called all_books in views.py, I get an error: UserProfileInfo matching query does not exist. Here's my all_books view: def all_books(request): if request.user.is_authenticated: context = { "books": Book.objects.all(), "request": request, "user_profile": UserProfileInfo.objects.get(user=request.user), } else: context = { "books": Book.objects.all(), "request": request, "user_profile": False, } if request.GET.get("context") == "mail_sent": context["mail_sent"] = True return render(request, 'main/all_books.html', context) This error happens only when I've signed in, and not when I'm not signed in. When I head over to the admin, I see that the profile has been created. But I don't understand why this isn't able to get that. -
docker + REST API in django
i have API project with python that work OK. after building a docker image it return this error: module 'keras.backend' has no attribute 'get_session' and then it doesn't work anymore. does anybody have an idea what should i do? I am on Ubuntu with python=3.8.10 requirments: tensorflow==2.4.0 tensorflow-gpu==2.4.0 keras==2.4.3 numpy==1.19.3 pillow==8.1.1 scipy==1.4.1 h5py==2.10.0 matplotlib==3.3.2 keras-resnet==0.2.0 Django==3.2.10 djangorestframework==3.13.0 opencv-python imageai -
Django to Heroku, How to migrate sqlite3 data to postgres
I tried to host a website on heroku but I keep getting this error File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "home_product" does not exist LINE 1: ...home_product"."price", "home_product"."slug" FROM "home_prod... whenever I tried to use heroku run python manage.py migrate -a appname I mainly used this video as a reference to hosting: https://www.youtube.com/watch?v=UkokhawLKDU&t=964s and also these articles which didn't really help tbh: Heroku Django Database Error https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment Here's my settings.py Django settings for Corbett_Jewelry project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url from decouple import config import psycopg2 # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', … -
How to prevent form update conflict among multiple users in Django?
I have a form like a student form. It can be updated by a function in view. There are multiple users that have the update permission for this form. The problem is when 2 users open the form of a student(id=1) at the same time. They can change fields and save the form. All changes of a user will be ignored and lost. How to prevent this conflict. I want if a user opens a specific student form, other users can not open it until the first user close the form or it's time for the update be expired. -
How to convert javascript object to python readable
I'm trying to parse below object from javascript post data into python using ast.literal_eval(obj) but ending up into below error Error: malformed node or string: <_ast.Name object at 0x7fb484eb8070> Object Value: '[{"dose":"1","duration":"2","name":"Item1","code":"pharma2","usage":{"morning":true,"afternoon":false,"evening":false,"night":false,"sos":false}},{"dose":"1","duration":"4","name":"Item2","code":"pharma1","usage":{"morning":false,"afternoon":false,"evening":false,"night":true,"sos":false}}]' -
How to choose one item in many to many relationship as special?
What is the best practice to choose one item from a m2m relationship? Lets say I've got an album of photos: class Photo(models.Model): img = models.FileField() class Album(models.Model): photos = models.ManyToManyField("Photo") But now I also want to pick one photo as a cover. I could use a Foreign Key in Album to one Photo, but then I'd always need to check whether this photo is actually in the photos of that album. Is there a better way? Sorry for the basic question I just somehow can't find the right words to google it. Thanks, Michael -
How to pass Django InMemoryUploadFile to serializer in case with images?
I'm creating an API using Django Rest Framework to save images from file directly or from url. I've got no problem with first case but with second. So, my models looks like this: class Image(models.Model): picture = models.ImageField(upload_to="site_media", blank=True) url = models.URLField(null=True, blank=True, max_length=255) parent_picture = models.IntegerField(null=True, blank=True) @property def name(self): return os.path.split(self.picture.name)[-1] @property def width(self): return self.picture.width @property def height(self): return self.picture.height Next, my serializer class: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = [ 'id', 'name', 'url', 'picture', 'width', 'height', 'parent_picture' ] The main idea is if you pass the URL while post request, API needs to download image from this URL and store it in database. To do this I overwrote create method in Django Rest Framework ModelViewSet class: from io import BytesIO import urllib import os from django.core.files.uploadedfile import InMemoryUploadedFile from PIL import Image as PILImage from rest_framework import status from rest_framework import viewsets from rest_framework.response import Response from .models import Image from .serializers import ImageSerializer class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer queryset = Image.objects.all() def create(self, request, *args, **kwargs): if request.data["url"]: url = request.data["url"] image_extensions = { ".jpg": "JPEG", ".jpeg": "JPEG", ".png": "PNG", ".gif": "GIF" } image_path = urllib.parse.urlparse(url).path image_filename = image_path.split("/")[-1] extension = os.path.splitext(image_filename)[-1] …