Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Proper way to build web app with Django on remote web server
I'm fairly new to Django so please excuse my ignorance. I'm starting my first build of a web app on my remote web server. I am currently SSH'ing to the server and have started the Django project. I just launched the development server for the Django project, and it automatically serves at http://127.0.0.1:8000/. My question is- what is the proper way to build a Django web app remotely on a server? Am I supposed to build the app on my computer and then transfer the project to my web server after it is complete? Or is there a way for me to access the development server without messing with the domains/ip addresses of the websites that are live on my web server? Thanks! -
Write django widget from forms.ModelForm to Forms.Form
I would like to use a custom widget in my forms.py file. I wrote this widget for forms.ModelForm with Meta class. But I would like to write the same thing for forms.Form. This is my forms.py file : class CustomFileInput(forms.widgets.ClearableFileInput): template_name = 'app/widgets/clearable_file_input.html' class FileUploadForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = FileUpload fields = ['file', 'site'] widgets = { 'file': CustomFileInput(attrs={'class': 'clearablefileinput'}) } How I can write something like this : class CustomFileInput(forms.widgets.ClearableFileInput): template_name = 'app/widgets/clearable_file_input.html' class FileUploadForm(forms.Form): file = forms.FileField(required=True, label=_('File upload'), widget=CustomFileInput()) site = forms.CharField(...) It doesn't work up to now. My widget file looks like this : {% if widget.is_initial %}{{ widget.initial_text }}: <a href="{{ widget.value.url }}" target="_blank">{{ widget.value }}</a>{% if not widget.required %} <input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}" /> <label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label>{% endif %}<br /> {{ widget.input_text }}:{% endif %} <input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %} /> -
Django POST from links to the view that is not specified in URL
The page signup.html have url as shown urls.py urlpatterns = [ ... path('signup', views.Sign_up,name="signup"), ... ] signup.html <form class="signup-form initial-signup-form gtm_signup_register_form" action="." accept-charset="UTF-8" method="POST"> ... </form> But when the form is submitted instead of accessing Signup() view,it points to Login_view(). I got output as "invalid login details supplied!". But the expected output is home.html. views.py def Sign_up(request): Fname = request.POST.get("first_name") Lname = request.POST.get("last_name") Mno = request.POST.get("Mobile") email = request.POST.get("email") Pass = request.POST.get("pass") Role = request.POST.get("role") Loc = request.POST.get("self_loc") if request.method == "POST": userM = UserManager() if Role=="Consumer": userV= userM.create_user(Mno,Role,Pass) else: userV= userM.create_staffuser(Mno,Role,Pass) userV.first_name=Fname userV.last_name=Lname userV.email=email userV.location=Loc return render(request, "home.html", {}) else: return render(request, "registration/signup.html", {}) def Login_view(request): print(request.method) if request.method == "POST": Uname = request.POST.get("Mobile") PassW = request.POST.get("password") print(Uname, PassW) user = authenticate(mobile_no = Uname, password=PassW) if user: if user.is_active: login(request,user) if user.is_staff: return HttpResponseRedirect(reverse('index')) else: return HttpResponseRedirect(reverse('home')) else: return HttpResponse("Account Not Active") else: print("Someone tried to login and failed") print("Mobile_no: {} and password {}".format(Uname,PassW)) return HttpResponse("invalid login details supplied!") else: return render(request,"registration/login.html", {}) -
How to get access token in apiview
I want to get access token in my APIView. I am using Oauth2 with client_credentials. Even it is printing self.request.auth and self.request.user as None. I want the user who have create client_credentials application in djnago restframework. # Employee API class EmployeeListAPIView(generics.ListAPIView): serializer_class = UserSerializer # permission_classes = [UserIsAuthenticated] def get_queryset(self, *args, **kwargs): print('request.user', self.request.auth) print('request.user', self.request.user) print('Access Token', self.access_token) qs = User.objects.exclude( Q(userprofile__user_is_deleted = True)| Q(userprofile__user_company__company_is_deleted=True) ).filter( Q(userprofile__user_company =self.request.auth.application.company) & Q(userprofile__user_role__id=4) ) return qs -
POST Body is not being sent with APIClient DRF
I'm fairly new to Django and have a solid background in Laravel (if you happen to make an analogy that would be awesome) I'm trying to pass a body to an end-point and I'm not being able to do it. I have tried: fake = Faker('pt_PT') fake.add_provider(company) client = APIClient() class CompanyPostTestCase(APITestCase): def setUp(self): self.email = fake.email() self.username = str(fake.company()).split()[0] self.valid_payload = { 'email': self.email, 'password': '123', 'username': self.username } def test_company_was_created(self): response = self.client.post('/v1/company/', self.valid_payload, # Also tried with content_type='application/json' format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) But when executing in debug mode the response object has POSTinside _closable_objects with QueryDict: {} which I'm assuming no body is specified. Also the error message says b'{"message":"You must provide a password"}' which clearly shows the body is not being passed. Via Postman I'm able to make the same request and create a Company without any problem. Any idea would be awesome to solve such a problem. -
Django + nginx large files upload
I am trying to upload a 2GB file in django using nginx. The file is uploaded upto 100% and then suddenly it terminates and 502 Bad Gateway error is displayed in nginx. Below is my application configurations upstream app_server { server unix:/home/training/run/gunicorn.sock fail_timeout=0; } server { listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name training.academy; keepalive_timeout 30; client_max_body_size 4G; access_log /home/training/logs/nginx-access.log; error_log /home/training/logs/nginx-error.log; location /static/ { alias /home/training/trainingapp/static/; } location /media/ { alias /home/training/trainingapp/media/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_read_timeout 1200; proxy_connect_timeout 1200; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_pass http://app_server; proxy_intercept_errors on; } } And below is the gunicorn start configs #!/bin/bash NAME="training" DIR=/home/training/trainingapp USER=training GROUP=training WORKERS=300 TIMEOUT=1200 BIND=unix:/home/training/run/gunicorn.sock DJANGO_SETTINGS_MODULE=training.settings DJANGO_WSGI_MODULE=training.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- How can I correct this error so that i can get a full and complete upload of the file and not the 502 error? -
Rendering Folium Map on Django Sever results in 'None'
i'm attempting to built a folium map that displays airbnb data from a collection of opendata. Outside of the django project in a pure python project I can compile the folium html file, open it and view all the marker clusters and markers themselves. However, I attempted to move this to a django server where a form takes user input requirements (min price, max price, guest number to accommodate) and when it comes to saving and rendering the folium map, it results in 'None' on the webpage. I understand this is an issue with the map object but i'm not sure how to get it to display correctly on the subsequent page after entering via the form. I am also aware that the map will be redmade each time upon a successful POST request (this is okay as it's not being desinged to handle many requests views.py from django.shortcuts import render from .form import ContactForm import folium from folium import LayerControl from folium.plugins import MarkerCluster import pandas def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): min = form.cleaned_data['min'] max = form.cleaned_data['max'] accom = form.cleaned_data['accommodates'] # import dataset airbnb_data = pandas.read_csv('data/listings_detailed.csv') meanLat = airbnb_data['latitude'].mean() meanLon = airbnb_data['longitude'].mean() # … -
Set object in Django @schema(AutoSchema(manual_fields=
I'm working in a django rest api that recieves an object in an endpoint. Some of the object attributes are required some are not. I want to show this in the documentation, but i don't know how to show the object with manual fields. Right now i have just the name of the object like: @schema(AutoSchema(manual_fields=[ coreapi.Field("node", required=True, location="query", description="Node Object") ])) This is shown in the documentation like this: -
Migrating Django application to alternate database only
I have a Django project with multiple applications. I want one of these applications (named warehouse) to go to a specific database (also named warehouse), but it doesn't seem to work as I expect. When I migrate this app from the command line (python manage.py migrate warehouse), I get a success message: >>> python manage.py migrate warehouse Operations to perform: Apply all migrations: warehouse Running migrations: Applying warehouse.0001_initial... OK The migration appears in my default database (in the django_migrations table), but no tables get created. If I change the command to the following: >>> python manage.py migrate warehouse --database=warehouse the tables show up in my warehouse database correctly, as does the migration. How can I change things so that the first command throws an error, or at least indicates that the given application cannot be applied to the default database? Here's my setup: Database Setup in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'projects', 'USER': 'myuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', }, 'warehouse': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'projects-warehouse', 'USER': 'otheruser', 'PASSWORD': 'otherpassword', 'HOST': 'localhost', 'PORT': '5432', }, } DATABASE_ROUTERS = ['warehouse.dbrouter.WarehouseRouter', 'base.dbrouter.BaseRouter'] dbrouter.py [Warehouse App] class WarehouseRouter: def db_for_read(self, model, **hints): if(model._meta.app_label == 'warehouse'): return 'warehouse' return … -
Extending social-auth-app-django with a custom User model
I am using Django v2 and social-auth-app-django. I have successfully made the user authenticate using Google+, and it updates my Users table under Authentication and Authorization with a firstname, lastname, email, username and staff status. I want to extend the current model so that it can take in more fields. Something like creating a profile after logging in for the first time. I do understand there are similar questions here, but none of them has complete answers. I am not asking for a full solution, but if someone can point me in the right direction, it'd be great. I am just starting with Django, and the docs can be a bit complex. Any help will be appreciated. Thank you. -
How to deploy Django Application along with Django Channels?
I have written a Django server that uses Django channels 2.0 and Rest Framework. I wanted to know how to deploy it for production. I know python manage.py runserver is used only for development server. But I am not sure how to deploy it for production. I have found various articles but it all has confused me. I read that I can use gunicorn and nginx to host an wsgi application but since the application is now asgi based rather than wsgi based. I am not sure how to put it to production? Can you please help me with this. Thanks in advance -
Django Dynamic Forms ManytoManyField
I have a problem that I want to make a football league page that can submit the starting XI list. But I don't know how to build the Dynamic Form. User (which is the team owner) can Login to choose the match to upload the starting XI. Website will show up the player list of the Team and let the User select Max of 11 and submit. The important thing is How can I generate the form with the Players belongs to Team. How to let the User upload Home / Away (The team belongs to User) starting XI only. Model.py class Schedule(models.Model): schedule_name = models.CharField(max_length=7, choices=LEAGUE_CHOICES, default='nil') schedule_home = models.ForeignKey(Team, on_delete=models.CASCADE,default='',related_name='schedule_home') schedule_away = models.ForeignKey(Team, on_delete=models.CASCADE,default='',related_name='schedule_away') class Player(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) player_name = models.CharField('Player Name', max_length=30, unique=True) player_team = models.ForeignKey(Team ,on_delete=models.SET_DEFAULT, default=1) class Team(models.Model): team_name = models.CharField('Team Name', max_length=30, unique=True) team_owner = models.OneToOneField(User,on_delete=models.CASCADE,related_name='owner') class Match_Starting(models.Model): starting_schedule = models.OneToOneField(Schedule,on_delete=models.CASCADE) home_starting = models.ManyToManyField(Player,blank=True,related_name='home_starting') away_starting = models.ManyToManyField(Player,blank=True,related_name='away_starting') @receiver(post_save, sender=Schedule) def create_match_stat(sender, instance, created, **kwargs): if created: Match_Starting.objects.create(starting_schedule=instance) -
Static files not getting loaded even in my Django admin page
I followed the below tutorial to create a Django blog application, but static files are not working even in admin page. https://tutorial.djangogirls.org/en/ I haven't added any static files to the application. my settings.py is below """ Django settings for jan_site project. Generated by 'django-admin startproject' using Django 2.0.10. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/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 = True ALLOWED_HOSTS = ['a.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jsite', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'jan_site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'jan_site.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS … -
I have reference unique id I need create a shareable link. like \n http//port//common url//refernce_id//
I have reference unique id I need create a shareable link. like \n http//port//common url//refernce_id// how to create a link please anyone suggest me -
Django ORM simple Join
I want to perform simple join operation like this. raw SQL : select * from risks r join sku_details s on r.sku_id = s.sku_id; model Details: class SkuDetails(models.Model): sku_id = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=65535) sku_desc = models.TextField(blank=True, null=True) category = models.TextField(blank=True, null=True) class Risks(models.Model): risk_id = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=65535) risk_group_short_desc = models.TextField(blank=True, null=True) risk_group_desc = models.TextField(blank=True, null=True) var = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True) sku = models.ForeignKey(SkuDetails, models.DO_NOTHING, blank=True, null=True) After joining I want all the column of both the table in flat structure through Django ORM... In raw SQL I will get all the column ... But not getting from ORM Please Help !!! -
Error when trying to render Folium map on Django Server
view.py saving the map my_map.html my_map.html browser result result when visiting the page (where the map should be rendered) im not sure how to approach getting the html/js to work on the browser after the user has submitted their input via the previous html form... I have seemed to look eveywhere and there are a lot of similar problems with solutions but I could not get any to work... Thanks! -
Django dont accept new url
Good day, I'm a absolut beginner with Python and Django. I'm following the book step of Nigel George and everything working fine until I try to add a url in the views.py to print Hello Word. If Anybody can help me. I try different thing but I don't get it. It should be simple and work. Thanks jre2 is my virtualenv and jre_web is my django site. I'm using django 1.8.13 for this book. I try django 2.1 and I have the same error. Here the content of views.py `from django.http import HttpResponse def hello(request): return HttpResponse("Hello world")` And here the urls.py `from django.conf.urls import include, url from django.contrib import admin from jre_web.views import hello urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url('^hello/', hello), ]` Here the error I got. IndentationError at / unexpected indent (views.py, line 3) Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.8.13 Exception Type: IndentationError Exception Value: unexpected indent (views.py, line 3) Exception Location: C:\Users\Minitaur\jre2\jre_web\jre_web\urls.py in , line 17 Python Executable: C:\Users\Minitaur\jre2\Scripts\python.exe Python Version: 3.7.2 Python Path: ['C:\Users\Minitaur\jre2\jre_web', 'C:\Users\Minitaur\jre2\Scripts\python37.zip', 'C:\Users\Minitaur\jre2\DLLs', 'C:\Users\Minitaur\jre2\lib', 'C:\Users\Minitaur\jre2\Scripts', 'c:\python\Lib', 'c:\python\DLLs', 'C:\Users\Minitaur\jre2', 'C:\Users\Minitaur\jre2\lib\site-packages'] -
Django - accessing a project prom another project
I've built a little project in Django- a rol web, with a user system and etc. Now I want to host it under my personal web, which is another Django project with info about myself. Is there any way to "import" the rol project in order to access it with a button from my personal web? If that's so, how efficient would it be? Could I add a "personal projects"-portfolio like tabs with urls leading to different projects, all stored under then same project? Thanks -
Django template: part of html condition
I'm working with a Javascript file that adds an attribute to a <div> of my html. $(".btnAuxDesde").click(function(){ $("#id_auxi_espec").val(""); $(".modalMapeo").attr('tipo', 'desde_hasta'); $("#mapeos_auxis").modal("show"); }); The important part here is the line where I add the attr tipo to the div with class modalMapeo. Having this, I'm making (or trying to) django show different types of buttons depending on the value of the attr tipo in the main <div> of this modal. What I need to do would be something like: {% if modalMapeo.tipo == 'desde_hasta' %} #some code {% elif modalMapeo.tipo == 'another tipo' %} #some other code {% endif %} But this syntaxis is wrong and I can't figure how to make django check this value in template. -
Django Diff between Dates
I have a project in django and i am trying to render html to pdf. I'm trying to build a table, and i have two varaibles date1 and date2 and i need to do a Diff between date1 and date2. If the result is more than 20 woriking days show 1 if not show 0 MY HTML {% for item in obj %} <tr> <td> {% if item.date1 - item.date2 > 20 %} 1 {% else %} 0 {% endif %} </td> </tr> {% endfor %} -
DEBUG = False returns an Server Error (500) in Django
When I changed the variable DEBUG in my Django app to False, even though I changed the allowed hosts to ['*'], I got the Server Error (500). Here is my settings.py file: import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'Clientes.apps.ClientesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectfield', 'crispy_forms', 'djrill', 'redactor', 'django_cron', 'rest_framework', 'rest_framework.authtoken', 'import_export', ] CRON_CLASSES = [ 'Clientes.cron.MyCronJob', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser', ), } TEMPLATE_CONTEXT_PROCESSORS = ( 'django_admin_dialog.context_processors.django_admin_dialog', ) ROOT_URLCONF = 'Checkstore.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Checkstore.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'mysite.log', 'formatter': 'verbose' }, … -
Running Chained Celery tasks at specific times
How can I use a celery chained task, such that the second task runs at a specific time i.e 10:04 PM task 1 -> task 2 (scheduled for tomorrow at 9am) -
django rest_framework caches sql queries
I am new to Django and React. I am taking over a Django / React project and have an issue where an api url is called: GET /api/admin/parents/ but the underlying sql statement: from django.http import HttpResponseRedirect from django.db.models import Q from .models import * from rest_framework import permissions, status from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.generics import ListAPIView, ListCreateAPIView, CreateAPIView, RetrieveUpdateAPIView, DestroyAPIView from .serializers import * from twilio.rest import Client class AdminAllParentsView(ListAPIView): serializer_class = UserSerializer queryset = User.objects.filter(is_staff=False, is_parent=True, is_active=True) does not get re-executed each time the GET /api/admin/parents/ call is performed. Say for instance.. a sql record is changed so that there are fewer records matching the is_parent=True part of the api call / query... the results returned by the api call don't reflect the real / current status of the query. The GET /api/admin/parents/ still returns the data from a previous, sql query ( a cached version I assume ) and does not re-execute the query. The urls.py part of this is: from django.urls import path from rest_framework_jwt.views import obtain_jwt_token from .views import * urlpatterns = [ path('admin/parents/', AdminAllParentsView.as_view()) So how to I get current sql data from this … -
Input search not working in Edge, IE, or Firefox
The search bar works in Chrome and Opera but not in the browsers named above. I suggest it has something to do with the onsearch="search(event)". Mozilla say's its not supported and I was wondering if anyone knew of a solution to this issue? HTML: <input type=search name="" id="filterSearch" placeholder="Search for events, seasonal meals or simply list ingredients" onsearch="search(event)" > -
Django serializer get related field
I have a querySet that I want to turn into a json and send to the client. It only needs some of the fields, as defined. However, the 'sender' shows up as a id because it is a foreignKey. What would be needed to return the senders username instead? (sender.username didn't work). (Not using drf) messages = Message.objects.all() messages_json = serializers.serialize("json", messages, fields=('id','sender', 'text', 'timestamp'))