Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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] … -
Django Admin Templates - How to add a "back to list" button?
Working with Django admin - still pretty new. I need to add a button to the footer (that appears when editing or adding an object) that sends the user back to the list page for that object. I am able to add the button itself to the footer by adding templates/admin/submit_line.html: {% load i18n admin_urls %} <div class="submit-row"> {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" {{ onclick_attrib }}/>{% endif %} {% if show_delete_link %}<p class="deletelink-box"><a href="{% url opts|admin_urlname:'delete' original.pk|admin_urlquote %}" class="deletelink">{% trans "Delete" %}</a></p>{% endif %} {% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" {{ onclick_attrib }}/>{%endif%} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" {{ onclick_attrib }}/>{% endif %} {% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" {{ onclick_attrib }}/>{% endif %} <input type="submit" value="{% trans 'Go Back' %}" {{???}}/> </div> But I don't know where to go from there. Presumably it is possible because Django breadcrumbs exist (and the relevant page is always the most recent link in the breadcrumbs), but I don't know how I'm supposed to get the link to the relevant page. -
when ever i am adding def str function to name it the model gives error
def __str__(self): return self.category_name when ever i am adding this str function in my model class Category(models.Model): category_name = models.CharField(max_length=50, unique=True,blank=True,null=True) slug = models.SlugField(max_length=100, unique=True,blank=True,null=True) description = models.TextField(max_length=255, blank=True,null=True) cat_image = models.ImageField(upload_to='photos/categories', blank=True,null=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('core:category', args=[self.slug]) then it gives me error TypeError at /admin/core/product/ str returned non-string (type NoneType) -
Passing Django view data to JavaScript Chart
I have some data that is returned via Django view, I'm trying to render the data in an Apex Pie Chart. So I need to pass the data into JavaScript as this is where the data series is. var pieColors = getChartColorsArray("#pie_chart"), options = { chart: { height: 320, type: "pie" }, series: [44, 55, 41, 17, 15], labels: ["Series 1", "Series 2", "Series 3", "Series 4", "Series 5"], colors: pieColors, legend: { show: !0, position: "bottom", horizontalAlign: "center", verticalAlign: "middle", floating: !1, fontSize: "14px", offsetX: 0 }, responsive: [{ breakpoint: 600, options: { chart: { height: 240 }, legend: { show: !1 } } }] }; (chart = new ApexCharts(document.querySelector("#pie_chart"), options)).render(); How do I pass the data in as it needs to be dynamic in the sense that the data in the pie chart could change based on other actions within the app? Should just embed the JS into my HTML template and then set the series values to series: [{{ value.1 }}, {{ value.2 }}, ...], Thanks -
LeaderboardAPI : I want to show only Today's record by comparing it with the created date
My Modely.py I am storing playername, TotalPoints, created_date by POST API from django.db import models from django.utils.translation import ugettext as _ # Create your models here. class leaderboard(models.Model): name = models.CharField(_("playername"), max_length=255) TotalPoints = models.IntegerField(_("TotalPoints")) created_date = models.DateTimeField(auto_now_add=True) My Serializers.py file: This is my Searializer: from rest_framework import serializers from .models import leaderboard class leaderboardSerializers(serializers.ModelSerializer): class Meta: model = leaderboard fields = [ 'name', 'TotalPoints', ] class lwithcdateSerializers(serializers.ModelSerializer): class Meta: model = leaderboard fields = [ 'name', 'TotalPoints', 'created_date', ] My Views class Leaderboard(APIView): def get(self, request, formate=None, **kwargs): today = datetime.date.today() serializer = lwithcdateSerializers(leaderb.objects.all().order_by('-TotalPoints') [:40], many=True) return Response(serializer.data) Please check the above code and let me know how can I display only Today's record -
Django - Changed DB from Sqlite3 to Postgres - do I need to do something else to reflect changes?
In my server, I changed the DB to Postgres from SQlite3. Because this is a new website and doesn't have much data yet (except test stuff) I didn't have to do DB migration or whatever else it is called. I just changed settings.DATABASES to include Postgres. Here's my settings.DATABASES in settings.py: from sys import platform if platform == 'darwin': # OSX DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR + '/db.sqlite3', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pfcbookclub', 'USER': 'admin', 'PASSWORD': 'g&zy8Je!u', 'HOST': '127.0.0.1', 'PORT': '5432', } } I develop on an M1, and psycopg2 doesn't seem to work for me, how many ever times I try to install libq or openssl with Homebrew on Rosetta, which is why I decided to use Sqlite on my Mac and Postgres on my server. Now, when I pulled these changes with git onto my server, I refreshed the page on my domain, but all the test data I had filled in my Sqlite3 database still showed. I thought it would be empty because I haven't filled up the Postgres DB with anything and I didn't do any sort of migration that would convert db.sqlite3 into Postgres … -
This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405
I am getting the following error message when I fill the form: This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405. Kindly advise. views: from django.shortcuts import render, get_object_or_404 from .models import Post from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import ListView from .forms import CommentForm from django.views import View class UltimatePostView(View): def get(self, request, slug): post = Post.objects.get(slug=slug ) context = { "post": post, "post_tags" : post.tag.all(), "comment_form" : CommentForm() } return render(request, "gold-blog/post-detail.html", context ) def post(self, request, slug): comment_form = CommentForm(request.POST) post = Post.objects.get(slug=slug ) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.save() return HttpResponseRedirect(reverse("post-detail-page", args=[slug])) context = { "post": post, "post_tags" : post.tag.all(), "comment_form" : comment_form } return render(request, "gold-blog/post-detail.html", context)