Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django customising template for form
SuspiciousOperation at /signup/ ManagementForm data is missing or has been tampered. Request Method: POST Request URL: http://localhost:8000/signup/ Django Version: 3.2.9 Exception Type: SuspiciousOperation Exception Value: ManagementForm data is missing or has been tampered. Exception Location: C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\formtools\wizard\views.py, line 282, in post I was trying to change my templates by adding 2 buttons for the forms and got this error. It displays the two buttons but everytime I click one it doesn't submit correctly. I want to make the is_doctor field in the modal set to false or true depending on the button click. from django.shortcuts import redirect, render from .forms import PickUserType, SignUpForm, UserProfileForm from django.contrib.auth import login, authenticate from formtools.wizard.views import SessionWizardView def show_message_form_condition(wizard): # try to get the cleaned data of step 1 cleaned_data = wizard.get_cleaned_data_for_step('0') or {} # check if the field isDoctor was checked. return cleaned_data.get('is_doctor')== False def process_data(form_list): form_data = [form.cleaned_data for form in form_list] print(form_data) return form_data WIZARD_FORMS = [("0", PickUserType), ("1" , SignUpForm), ] TEMPLATES = {"0": "pickUserType.html", "1": "createUser.html"} class ContactWizard(SessionWizardView): def done(self, form_list, **kwargs): process_data(form_list) return redirect('home') def get_template_names(self): return [TEMPLATES[self.steps.current]] forms.py from django import forms from django.core.files.images import get_image_dimensions from django.forms.widgets import RadioSelect from pages.models import Profile from django.contrib.auth.forms import UserCreationForm … -
Django + Channels: message interrupted by posting
I am coding a page that contains a form to create a game (several field) and just below a list of all the created games. When I post the new game, I would like the list of games to refresh for all the connected users of the page. My consumer.py: def receive(self, text_data): games = serialize_games() # Send new game info to Lobby async_to_sync(self.channel_layer.group_send)( 'Lobby', { 'type': 'message_to_lobby', 'message': games, }) def message_to_lobby(self, event): print('messages sent to lobby') message = event['message'] self.send(text_data = message) In my template I have a jquery portion of code that sends message to the websocket just prior the post is submitted: $("#create_game_form").submit(function(e) { alert('sent');LobbySocket.send(JSON.stringify({ 'message': 'reload' }));}); During the posting, the receive function is well called, whereas the message handler (message_to_lobby) is not, since the rendering in the view section disconnect the websocket before... Would it help to use async functions instead (I don't really see why...)? Or maybe Django + Channels are not meant to make POST and channels work together? Otherwise, I may have the possibility to ask for the consumer to send an update signal to group users very 2sec or something like this, but I don"t find it very elegant. -
How to create blob url from normal url in react
I'm building a website that provides quality videos for students. So I want a feature that is students don't see the URL of the video. How I implement that feature on Reactjs. I used technologies Django and ReactJS. -
What traffic level is good for Sqlite?
I'm using Sqlite3, and I want to be sure it's good for me. The traffic I kinda get will be 'round 2500 - 5000 people * how many apartments choose to use the service, because this is for communities, like an apartment complex, to use. I'm using Django, and the things that I had developed using Sqlite on my local don't work well with the Postgres I have on my server. So I thought that I could just use Sqlite and migrate to Postgres only later. So I want to know until when can I use Sqlite? -
DRF - Using custom permission class as default permission class
In my django project, I have created an app called 'base' in which the files are structured as follows: backend | |--app (created via startproject) | | | |--settings.py | |--base (created via startapp) | |--permissions | | | |--init.py | | | |--IsActivatedAccount.py | |--views |--serializers As you can see, I have created a 'permissions' package in which I have created a custom permission class called 'IsActivatedAccount'. Here is how the files look: init.py: from .IsActivatedAccount import * IsActivatedAccount.py: from rest_framework.permissions import BasePermission from ..models import * class IsActivatedAccount(BasePermission): message = 'Email verification pending' def has_permission(self, request, view): return request.user.status != User.Status.PENDING_ACTIVATION Now, I am trying to use this permission as the default permission class in combination with IsAuthenticated permission class from django-rest-framework. Here is how I have added it in settings.py of the project. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'base.permissions.IsAccountActivated', ], } Due to 'base.permissions.IsAccountActivated', the server is failing to start and here is the error that I am getting: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/mouli/.local/share/virtualenvs/backend-yIk9pObI/lib/python3.8/site-packages/django/utils/module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "/home/mouli/.local/share/virtualenvs/backend-yIk9pObI/lib/python3.8/site-packages/django/utils/module_loading.py", line 16, in cached_import return getattr(modules[module_path], class_name) AttributeError: module 'base.permissions' has no … -
How to filter by range OR "null" value? (I.e. combine NumberFilter range and BooleanFilter for null=True IntegerField)
I have a Item model with a numeric number field. This number field defaults to null. # models.py class Item(models.Model): number = models.IntegerField(default=None, blank=True, null=True) I want to set-up filters that can return a queryset of Items where number is in range - which is straightforward enough: # filters.py class ItemFilter(django_filters.FilterSet): min_num = django_filters.NumberFilter(method="min_num_filter") max_num = django_filters.NumberFilter(method="max_num_filter") class Meta: model = Item fields = ("min_num", "max_num", "incl_null") def min_num_filter(self, queryset, name, value): return queryset.filter(number__gte=value) def max_num_filter(self, queryset, name, value): return queryset.filter(number__lte=value) But what if I want to have an additional Boolean filter that can include Items that has null for number along with whatever Items matches the min_num and max_num range? So for example, a URL query in the form of ?min_num=1&max_num=10&incl_null=True should return all Items where number is between 1 and 10 OR number is equal to None. The following code does not work: class ItemFilter(django_filters.FilterSet): ... incl_null = django_filters.BooleanFilter(method="incl_null_filter") class Meta: model = Item fields = ("min_num", "max_num", "incl_null") // doesn't work class incl_null_filter(self, queryset, name, value): if value is True: return queryset | Item.objects.filter(number=None) if value is False: return queryset -
Is it possible to integrate Stripe Subscriptions using dj-stripe into a Django application that already has category, products, and order models built
I'm building a fitness subscription application with Django, Python, and Stripe. Since I will be selling a variety of products, workout plans, nutrition plans, and merchandise I wanted to implement a subscription based payment model. I have already built apps and models for Categories, Products, and orders and am just now looking at integrating the payment model. (I have the shopping bag app and the beginnings of the checkout app built also) I've been looking at Stripe Subscriptions and it seems the most straight forward way of implementing it would be by syncing the data with dj-stripe, so I added the products through the stripe dashboard. But my concern is what will happen if/when I sync the data from Stripe to my application? I already have a sqlite3 db for development and a postgres db for production with all this data. Will the synced data just create a replica in the database or sync up to what's already there? I'm new to Stripe and Django and have tried to find this information online but am struggling to find an answer to this question. Any advice surrounding Stripe Subscriptions would be so so appreciated! Apologies if this question does not meet … -
My website was showing CSS fine until I did collectstatic - Django
My website was doing everything well and showing all the CSS until I ran collectstatic on it. Now everything is how it would look if CSS didn't exist. Is there any solution to this? Or is there some way I can delete the collectstatic to get back the previous thing? -
ModuleNotFoundError: No module named 'project.wsgi'
Trying to deploy my django application to elastic beanstalk using github actions but I'm getting ModuleNotFoundError: No module named 'project_pit.wsgi'. The project is deploying correctly to aws but it is Degraded after deploy. Github Action: jobs: build: runs-on: ubuntu-latest steps: - name: Checkout source code uses: actions/checkout@v2 - name: Generate deployment package & zip run: zip -r deploy.zip . -x '*.git*' - name: Get timestamp uses: gerred/actions/current-time@master id: current-time - name: Run string replace uses: frabert/replace-string-action@master id: format-time with: pattern: '[:\.]+' string: "${{ steps.current-time.outputs.time }}" replace-with: "-" flags: "g" - name: Deploy to EB uses: einaregilsson/beanstalk-deploy@v20 with: aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }} aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} application_name: project-pit environment_name: project-pit-cloud version_label: "app-${{ steps.format-time.outputs.replaced }}" region: ap-southeast-2 deployment_package: deploy.zip - name: Deployed! run: echo App deployed to ELB -
Hi there, how to i listen in django channels for the data/sms from different chats even if I m not inside of any specific room
Im trying to build a chat app with multiple rooms and i want to be able to listen for any data even if am not in any room, like whatsapp web, you can receive data of any user even if you are not inside that chat from where you are receiving data. -
Django form tools switch forms
I would like to make a conditional if is_doctor is checked else. So currently it will display the form if the form is checked now I would like to add another form if it isn't checked how would I attempt to do so? urls.py from django.urls import path from pages.views import index, ContactWizard, show_message_form_condition from pages.forms import PickUserType, SignUpForm contact_forms = [PickUserType, SignUpForm] urlpatterns = [ path('', index, name='home'), path('signup/', ContactWizard.as_view(contact_forms, condition_dict={'1': show_message_form_condition} ),name='signup'), ] forms.py from django import forms from pages.models import Profile from django.contrib.auth.forms import UserCreationForm from datetime import date, timedelta class PickUserType(forms.Form): is_doctor = forms.BooleanField(required=False) # verified = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'doctor')) # from django.core.files.storage import FileSystemStorage class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) views.py from django.shortcuts import redirect, render from .forms import SignUpForm, UserProfileForm from django.contrib.auth import login, authenticate from formtools.wizard.views import SessionWizardView def show_message_form_condition(wizard): # try to get the cleaned data of step 1 cleaned_data = wizard.get_cleaned_data_for_step('0') or {} # check if the field isDoctor was checked. return cleaned_data.get('is_doctor', True) class ContactWizard(SessionWizardView): def done(self, form_list,form_dict, **kwargs): print(form_list) print(form_dict) print(kwargs) … -
Two Django apps, two different nginx servers, cannot load static files on 2nd server from 1st server
I have two servers, test1.com and test2.com. Test1 is internet-facing public server. Test2 is intranet only server. Both servers have nginx docker running. Test1 runs a Django app1 which has static files under /app/public/static. App1 can load the static files and run correctly from URL https://test1.com/app1. Test2 has a Django app2 which has static files under /app/public/static on server test2 from URL https://test2.com/app2. Everything works including static files. The issue is I need to configure nginx1 to allow people to access app2 from the public internet. With the configuration nginx1 below I can load app2 but not the app2 static files. The error is: "GET /static/img/logo.jpg HTTP/1.1", host: "test1.com", referrer: https://test1.com/app2/ . The nginx is looking for app2 static file under test1 which obviously ‘file not found’. How can I configure nginx1 to look for app2 static files under test2.com, with a url of https://test2.com/app2/? : user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; client_max_body_size 50m; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log; sendfile on; keepalive_timeout 65; map $http_upgrade $connection_upgrade { default upgrade; '' close; } … -
how to upload a csv file with pandas to a Database created by Django and set the Graph with matplotlib
i created a data base useing Django, so far I made the path for the File to models.FileField the plan is when someone upload a csv file it will generate a graph and display it as .png in the html post detail template. models.py: class Post(models.Model): files_Modulus = models.FileField(null=True,upload_to="chapters/%Y/%m/%D",default='no_data.html) Each uploaded file have the path:\media\chapters\2021\12\12\31\21\test.csv How can I tell pandas to read every file will the user upload to that path in the models.py as upload_to="chapters/%Y/%m/%D"and make a graph useing matplotlib and save it as PNG file and place it in the HTML template. -
Overriding Django model save method with image resizing
The below code successfully override the save method class News(models.Model): ........... photo=models.ImageField() def save(self,*args, **kwargs): super().save(*args, **kwargs) img1 = Image.open(self.image1.path) if img1.height > 400 or img1.width > 400: output_size = (400,400) img1.thumbnail(output_size) img1.save(self.image1.path) But after super().save() code, image is being opened and saved. Is it an efficient method? how its possible to reopen image after saving . -
Standard superuser creation in Django admin give unrecognizable error
python manage.py createsuperuser --username='donfox' After password is entered this is returned raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.name, kwarg)) TypeError: User() got an unexpected keyword argument 'email' The User is extended from an "AbstractUser". class User(AbstractUser): email = None first_name = None last_name = None REQUIRED_FIELDS = [] def __str__(self): return self.email class Meta: db_table = 'User' Column | Type | Collation | Nullable | Default --------------+--------------------------+-----------+----------+------------------------------------ id | integer | | not null | nextval('"User_id_seq"'::regclass) password | character varying(128) | | not null | last_login | timestamp with time zone | | | is_superuser | boolean | | not null | username | character varying(150) | | not null | is_staff | boolean | | not null | is_active | boolean | | not null | date_joined | timestamp with time zone | | not null | -
How to merge list of dictionaries by unique key value [duplicate]
I want to merge list of dictionary provided below with unique channel and zrepcode. sample input: [ { "channel": 1, "zrepcode": "123456", "turn": 7833.9 }, { "channel": 1, "zrepcode": "123456", "pipeline": 324 }, { "channel": 1, "zrepcode": "123456", "inv_bal": 941.16 }, { "channel": 1, "zrepcode": "123456", "display": 341 }, { "channel": 3, "zrepcode": "123456", "display": 941.16 }, { "channel": 3, "zrepcode": "123456", "turn": 7935.01 }, { "channel": 3, "zrepcode": "123456", "pipeline": 0 }, { "channel": 3, "zrepcode": "123456", "inv_bal": 341 }, { "channel": 3, "zrepcode": "789789", "display": 941.16 }, { "channel": 3, "zrepcode": "789789", "turn": 7935.01 }, { "channel": 3, "zrepcode": "789789", "pipeline": 0 }, { "channel": 3, "zrepcode": "789789", "inv_bal": 341 } ] Sample output: [ {'channel': 1, 'zrepcode': '123456', 'turn': 7833.9, 'pipeline': 324.0,'display': 341,'inv_bal': 941.16}, {'channel': 3, 'zrepcode': '123456', 'turn': 7935.01, 'pipeline': 0.0, 'display': 941.16, 'inv_bal': 341.0}, {'channel': 3, 'zrepcode': '789789', 'turn': 7935.01, 'pipeline': 0.0, 'display': 941.16, 'inv_bal': 341.0} ] -
How do you implement Django namespaces
I have started my journey with Django and I am thoroughly loving it. I do have a question about namespaces which I hope someone will be able to help me with and explain why it works like that. I understand namespaces are used to make sure that if you have two pages with the same name that the url and reverse function points to the right page. I have been trying to implement namespaces in a test app I am writing but have not been able to do it. Here is what I have so far (This is without namespaces as I haven't been able to get it to work. Extract from app urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('', views.index, name = "index"), ] project urls.py from django.contrib import admin from django.urls import path, include, re_path import gallery urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('index/', include('gallery.urls')), ] And lastly, this is my view.py file in my app folder from django.shortcuts import render from django.urls import reverse # Create your views here. def index(request): return render(request,"gallery/index.html") Any help will be appreciated -
Simple WYSIWYG image uploading
Currently I am using ckeditor to allow users to write blog posts. It does everything I want except the image uploading is awful. Users have to jump through two screen to upload an image and specify dimensions. The images don't auto scale to mobile and overall its a very poor experience. Is there a simple way to allow users to upload images or another WYSIWYG that can handle this. -
Acessing SQLite tables with Django on Ubuntu
I am following the Django official documentation tutorial on how to setup the database, provided here : https://docs.djangoproject.com/en/4.0/intro/tutorial02/ After running the code below I should have any necessary database tables according to the database settings in my mysite/settings.py. $ python manage.py migrate Now I want to check those tables through the terminal (this is my problem -> I can't). The documentation says : If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MariaDB, MySQL), .tables (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created. None of those commands works on my terminal, my project is setup to be on SQlite, which is just a file on my project folder and SQLite is included in Python, so I shouldn't need to install anything else to support your database My questions is if I can ONLY run that command (.tables) on sqlite special command line and I need to install it or is there any way I can acess it with the terminal Iam using on Django. Any help will be HIGHLY appreciated. -
Django Tutorial - Testing vote(request, question_id)
I am working my way through the django tutorial and I reached part 5 - Introducing automated testing. I want to go beyond and write test for the vote method in views.py, but can't realise how to simulate the behaviour. Is there a way to do this? models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text views.py def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) I've tried multiple stuff in tests.py. This is the latest version - i know choice_vote is currently not what i want, still needs to be filtered: class QuestionVoteTests(TestCase): def test_vote(self): """ Placeholder for vote method test. """ question = create_question(question_text="Question.", days=-5) … -
URL error in Django, being asked to add semicolon in the url link object
I have an HTML link, upon clicking it will direct me to the respective link <div onclick="location.href='{% url 'newscountry' 'Kuwait' %}'"> Kuwait </div> But I am being warned to add ; in the above link (as {% url 'newscountry'; 'Kuwait' %}')as per the attached image. Also, I am getting inconsistent links results too. urls.py as below, path('country/<str:country>/',NewsCountryView.as_view(),name='newscountry'), views.py class NewsCountryView(ListView): model = News template_name = 'newsfront/index.html' # <app>/<model>_<viewtype>.html context_object_name = 'news' ordering = ['-date_posted'] paginate_by = 16 def get_queryset(self): country=self.kwargs.get('country') return News.objects.filter(country=country) -
Failed to exec Python script file '/myproject/myproject/myproject/wsgi.py'
When I deployed my project, got these errors: [Fri Dec 31 18:27:56.319749 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] mod_wsgi (pid=4064): Failed to exec Python script file '/myproject/myproject/myproject/wsgi.py'. [Fri Dec 31 18:27:56.319901 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] mod_wsgi (pid=4064): Exception occurred processing WSGI script '/myproject/myproject/myproject/wsgi.py'. [Fri Dec 31 18:27:56.320220 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] Traceback (most recent call last): [Fri Dec 31 18:27:56.320306 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/myproject/myproject/wsgi.py", line 16, in <module> [Fri Dec 31 18:27:56.320322 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] application = get_wsgi_application() [Fri Dec 31 18:27:56.320346 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Fri Dec 31 18:27:56.320359 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] django.setup(set_prefix=False) [Fri Dec 31 18:27:56.320381 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup [Fri Dec 31 18:27:56.320393 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] apps.populate(settings.INSTALLED_APPS) [Fri Dec 31 18:27:56.320415 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate [Fri Dec 31 18:27:56.320427 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] app_config = AppConfig.create(entry) [Fri Dec 31 18:27:56.320448 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/apps/config.py", line 224, in create … -
Can't measure the performance of serializer using cProfile
I'm trying to use cProfile to compare between serializers.ModelSerializer and serializers.Serializer according to this tutorial. Please, check out the tutorial before continuing the reading, it will be useful for you! Serializers: from django.contrib.auth.models import User from rest_framework import serializer class UserModelSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', ] class UserSerializer(serializers.Serializer): id = serializers.IntegerField() username = serializers.CharField() Views: from . serializers import UserModelSerializer, UserSerializer from rest_framework.response import Response from rest_framework.views import APIView import cProfile class TestApi(APIView): def get(self, request): u = User.objects.get(username='hamza') assert u.username == 'hamza' # just to ensure it fetches the user data = UserModelSerializer(u).data cProfile.run('for _ in range(5000): data') return Response(data) In views I just create GET endpoint and try to run cProfile but this gives me an error: NameError: name 'data' is not defined but if I comment the line cProfile.run('for _ in range(5000): data') in views and try to access data and send it to the Response without using cProfile it will work fine! So the question is, Why cProfile can't see UserModelSerializer? -
How to make the search-bar return "the post you searched doesn't exist" instead of displaying nothing https://github.com/Ayman-Isam/Class-of-2024-Blog
Here the searched function looks for the title of a post and searches it using the icontains functionality {% extends "blog/base.html" %} {% block content %} <div class="search-results"> {% if searched %} <h1>Results for - {{ searched }} </h1> <br> {% for post in posts %} <a href="{% url 'post-detail' post.id %}">{{ post }} - {{ post.description }}<br></a> {% endfor %} {% else %} <h1 class="find">You forgot to search for a post</h1> {% endif %} </div> {% endblock %} -
Issue with django json response
I have issue with json response. messages.values() gives me user_id instead of username. How to get username? Here is my code: class LivechatMessage(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE, null=True) def getMessages(request): messages =LivechatMessage.objects.all() return JsonResponse({"messages":list(messages.values())})