Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to position objects with initial values?
I have a page made in Django that allows dragging objects, what I do is save the position in X and Y of each object, I store the data in a database, I already have the data, now what I want to do is that when the page is updated, the position of the objects is maintained, already having this data in the database, how do I pass those coordinates to the objects so that when they update they remain in the same position? These are the variables where I have the coordinates: {{ qst.posX }} {{ qst.posY }} Part of the HTML CODE: {% if qst %} <div id="containment-wrapper"> {% for device in qsd %} <div id="{{ device.device_name }}" class="draggable"> <span class="dot" title="{{ device.device_name }}" style="background-color: #197f32"><br/><b><p style="color: #ce3830;"> {{ device.device_name }}</p></b></span> </div> {% endfor %} <button id="save">Save Position</button> </div> {% endif %} JavaScript: $(document).on("ready", function () { $(".draggable").draggable({ containment: "#containment-wrapper" }); }) $(document).on("mouseup", ".draggable", function () { var elem = $(this), id = elem.attr('id'), desc = elem.attr('data-desc'), pos = elem.position(); console.log('Left: ' + pos.left + '; Top:' + pos.top + '; ID:' + id); }); $('#save').on('click', function () { $(".draggable").each(function () { var elem = $(this), id = … -
problem with django url dispatcher , unable to resolve the url
i got latest django installed and working through hello world tutorial i got problem with getting url dispatcher working i got configured as follow in django_web/urls.py i got urlpatterns = [ path('TEST1', include('newpage.urls')), #path('admin/', admin.site.urls), ] in newpage/urls.py i got urlpatterns = [ path('', views.index, name='index'), path('TEST' ,views.index2, name='cokolwiek'), ] if i hit localhost:8000/TEST1 - works fine if i hit localhost:8000/TEST1/TEST - does not work i got followin message Using the URLconf defined in django_web.urls, Django tried these URL patterns, in this order: TEST1 [name='index'] TEST1 TEST [name='cokolwiek'] The current path, TEST1/TEST, didn't match any of these. how the hell is that not working -
Django: same Form inside for loop for different posts doesn't save state when other is applied to
I am trying to have this html gallery to show a for loop of posts, and inside each post is a form to fill out if they want to apply, I am passing the id through to the view from the template but when I submit one form, and then another, the first form doesn't show the success message anymore. So I can bounce between the same two posts and be able to apply to both infinity because the state resets each time. I need to make it to where it tracks the state of what's been applied to on the page without reloading the page. function submitMore(id) { $('#application-form-el'+id).submit(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/contact/career-applicant/', data: $('#application-form-el'+id).serialize(), success: function(data) { console.log(data.form_html) $('#plugin-wrapper-{{ section.id }}').html(data.form_html); }, error: function(data) { alert(data.form_html); }, }); e.preventDefault(); // avoid to execute the actual submit of the form. }); $('select').chosen({ disable_search_threshold: 20 }); } Here is the view method def view_career_applicant(request): success = False id = 0 json_data = {} career_thank_you = '' career_form = ApplicationForm(request.POST, request.FILES) # TODO: need to check id for submitting correct success message if career_form.is_valid(): job = Career_posting.objects.get(pk=request.POST['post_id']) # <--- post_id to connect to form. cleaned_data = career_form.cleaned_data applicant … -
django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
Below is my docker-compose.yml code. version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: testpassword volumes: postgres_data: Below is my Dockerfile code: # Pull base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ Upon runnning "docker compose up" in command, I receive the following message, ERROR: for db Cannot create container for service db: Duplicate mount point: /var/lib/postgresql/data ERROR: Encountered errors while bringing up the project. -
Wagtail Multi-sites vs Apache Virtual Hosts
I've been to this site countless times but never made an account. I'm working on my first big project, so, first question: I intend to make a few websites that will be sharing the same droplet instance from hosting provider (DO). Wagtail offers multiple-sites on a single codebase. It lets you manage all sites from a single dashboard. Apache lets you create multiple domains/individual websites - known as 'virtual hosts' - and directs the user to the specific directory where the requested website is located. The websites I'm working on will share a single database to a certain degree (one of the sites will act as checkout page for some of the other sites, for example, where cart contents are retrieved via api/jason (I don't know yet)) Wagtail seems to be the best choice but I want to make sure Apache isn't required regardless of how I solve this problem (ex: if DO requires apache to be able to serve my websites as opposed to directly serving from django, for example) tvesday -
Send activation email to Admin/Superuser on user signup in Django
I am trying to send an activation email to my inbox when a user signs up so I can choose whether to accept the user or not. Currently I have a sitewide permission that I just add to each user I want to allow but thought there might be a more efficient and cleaner method. -
adding required files to custome user when registration in django
I’m really new in Django and I would like to create a register form to login user. I would like this form have additional and required fields. the problem is when I try to fill the sign up registration directly on the web, the user is not registered, but if I do it in /admin section, the user is saved, so I have used custom user So first I have created class in model.py file: class Account (AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField( verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) phone_regex = RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField( validators=[phone_regex], max_length=17, blank=True) # validators should be a list role = models.CharField(max_length=50) store = models.CharField(max_length=50) aisle = models.CharField(max_length=50, unique=True) user_identification = models.CharField(max_length=30, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'phone_number', 'role', 'store', 'aisle', 'user_identification'] objects = MyAccountManager() def __str__(self): return self.email # if user is admin, can chenge def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True @property def … -
How to pass dynamic lookups from the request.GET right to filter?
Sending query like this /?field1=value1 in the request.GET i have {'field1': ['value1']}. So doing .filter(**request.GET) i send to it (field1=['value1']) instead of (field1='value1'). How i can take strings instead of arrays? -
React front-end to receive updates from a running process in Django back-end
I'm trying to generate a large PDF file that isn't feasible to do client-side. From the React FE, the user can select a category they want to run, and submit it to the Django BE. Django will then iterate through all of the items in that category to produce the PDF server-side, then send it to the FE when it is done. That much I pretty much have sorted out. However, what I want to implement is that as it is iterating through the items in the category, it is updating FE with which item is currently at, where it is in the queue, and how many total items are in the queue. From that, a percentage completed and an estimated time remaining can be calculated. A regular axios HTTP request doesn't seem like it would do the trick because it is terminated when it receives a response. Unless I iterate through the items in the FE and make an HTTP request for each item, but that doesn't seem like the best way to go about this. I'm just not sure what libraries I will need or what tech I need to be looking at to implement this, so that … -
Add a foreign key to AbstractUser
I have this two models: class User(AbstractUser): pass class Listing(models.Model): listing_id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') title = models.CharField(max_length=64) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="listing") I would like to do the following in the User model: class User(AbstractUser): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) But i'm getting the following error: NameError: name 'Listing' is not defined Is it possible to add a foreign key to abstractuser? -
Django Beginner: Display value of RawQuerySet
I am using a RAW SQL query to get the record of each week's sale and then sum it up and show it on the web page. Here's my query: sales = addCustomer.objects.raw("SELECT SUM(productPrice) FROM cms_addcustomer WHERE date <= %s and date >= %s", [startdate, weekDate]) Already using the datetime library to get the date and everything is working fine on this end. When I try to display the result I get this message on my webpage: Total Sales: Rs.<RawQuerySet: SELECT SUM(productPrice) FROM cms_addcustomer WHERE date <= 2020-07-29 and date >= 2020-07-23> Here is a screenshot. I just want to display the sum of the Sales on my webpage but I am not sure how to do it. I have read most of the answers on StackOverFlow but I was unable to understand them as I am complete beginner. Please help. Thank you. -
Django ForeignKey only delete "child" element
I've followed the starting tutorial and my admin page looks like this I am trying to delete a choice by selecting the "Delete?" option and clicking "Delete", but after doing so it prompts me to delete the entire question and its corresponding choices. How can I only delete individual choices? I've found that on_delete=models.CASCADE is most likely the culprit, and I've found the alternatives, but none of these seem to just simply remove the Choice and revert the question to the state it was before I added the Choice. I am a complete beginner and any help is much appreciated. -
How to use Pycharm with Virtual Environment / Django?
Good afternoon everyone, I recently finished working with pygame and now I'm starting to learn Django because I've always wanted to make my own website. Everyone who teaches Django tells their viewers they need a "virtual environment". I spent a whole day understanding what it is and how to create one, activate it, deactivate, install packages, pip freeze, etc etc etc.... I understood that part atleast the basics. I'm going to be using Pythons built in "venv" and not "virtualenv", "pipenv" or any other virtual environment tool. From what I learned about virtual environments, they recommend NOT to place stuff inside the virtual environment. Ok that I got... I've been using Pycahrm as my IDE and has helped me a lot to learn programming. My main question is: Will the way I use Pycharm change NOW that I'm getting into Django and virtual environments? With pygame or tkinter I just opened a new project (example: "robot_game") in Pycharm, a new directory was created with the name of "robot_game" and inside that folder another folder called "venv" was created. All my images, sounds and .py files where inside "robot_game", not inside "venv" folder. That was my normal rutine. ...but I remember … -
Django API does not accept data since its not recognized as a file
I have an ionic 5 project with Angular 9 that I want to connect with an Django rest api. I have problems when it comes to upload images and other stuff with it. I want to upload posts with other information like position, hashtags and so on. The data consists of a file, bools, numbers and strings. The api docs says its not JSON its multipart. When I try to post the payload it gives me this error: {"src":["The submitted data was not a file. Check the encoding type on the form."],"lon":["A valid number is required."],"lat":["A valid number is required."]} What is really strange is, that it says my data wouldn't be a file since I converted it to a file and the console actually also tells me it would be a file. This is what the form contains: image: ZoneAwarePromise __zone_symbol__state: true __zone_symbol__value: File {name: "picture.jpeg", lastModified: 1569954025000, lastModifiedDate: Tue Oct 01 2019 20:20:25 GMT+0200 (Mitteleuropäische Sommerzeit), webkitRelativePath: "", size: 274100, …} Symbol(Symbol.toStringTag): (...) __proto__: Object position_lat: ZoneAwarePromise {__zone_symbol__state: true, __zone_symbol__value: 10} position_lon: ZoneAwarePromise {__zone_symbol__state: true, __zone_symbol__value: 5} Here my code: camera.ts // convert base64 image into a file function base64toBlob(base64Data, contentType) { contentType = contentType || ''; const … -
Only check Django form if radio button is selected
I got one form in a Django checkout page where the user can select if their product is gonna be shipped to the regular address ou another one he/she desires. The case is: if the user uses the regular address, some fields do not need to be filled. Otherwise, if the costumer selects to be shipped to another address, Django must check if all form fields are properly filled. My form.py: class ProfileRegistrationForm(forms.ModelForm): class Meta: model = Profile fields = ('date_of_birth', 'cep', 'rua', 'numero', 'bairro', 'complemento', 'cidade', 'estado') labels = {'date_of_birth': 'Data de nascimento', 'cep': 'CEP', 'numero': 'Nº'} widgets = {'date_of_birth': forms.TextInput(attrs={'id': 'date_of_birth', 'OnKeyPress': 'formatar("##/##/##", this)', 'maxlength': "8", 'placeholder': '__/__/__', 'class': 'form-control'}), 'cep': forms.TextInput(attrs={'id': 'cep', 'onblur': 'pesquisacep(this.value)', 'OnKeyPress': 'formatar("#####-###", this)', 'placeholder': '______-___', 'class': 'form-control'}), 'rua': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'rua', 'class': 'form-control'}), 'bairro': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'bairro', 'class': 'form-control'}), 'cidade': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'cidade', 'class': 'form-control'}), 'estado': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'uf', 'class': 'form-control'}), 'numero': forms.TextInput(attrs={'id': 'numero', 'class': 'form-control', 'placeholder': 'Nº'}), 'complemento': forms.TextInput(attrs={'id': 'complemento', 'class': 'form-control', 'placeholder': 'Complemento'}),} The checkout.html template: <form action="" method="post" id="payment-form"> <div class="box-element" id="form-wrapper"> <div id="user-info"> <p><strong>{{ user.username }}</strong>, confira abaixo o endereço de entrega:</p> <p><input type="radio" name="address" checked="checked"> Endereço de entrega:<br> {{ user.profile.rua }}, nº {{ user.profile.numero … -
Django skips a url pattern?
In my urls.py, I have the following: urlpatterns = [ path("", views.homepage, name="homepage"), path('completed/', views.completed, name='completed'), path("<single_slug>", views.link_slug, name="link_slug"), ] When I'm testing locally, if I visit IP:8000/completed, it calls the completed() function in my views.py, but when I run it on Heroku (connect to www.WEBSITE.com/completed), it ends up skipping it, passing 'completed' into my link_slug() function. Here is my views.py: def completed(request): return render(request=request, template_name='main/completed.html', context={'categories':ProjectCategory.objects.all}) def link_slug(request, single_slug): #do stuff -
Second page of Pagination not working in django after searching
Searching result is not appearing in second page what should I change to solve my problem ? and I'm using elasticsearch as search engine index.html <ul> {% for i in paginator.page_range %} {% if i <= page_number|add:5 and i >= page_number|add:-5 %} <li class=" {% if i == page_number %} active {% endif %} " > <a href="?page={{forloop.counter}}">{{forloop.counter}}</a> </li> {% endif %} {% endfor %} </ul> and this is in my views.py def index(request): q = request.GET.get('q') if q: articles = PostDocument.search().query("match", title=q, ) paginator = Paginator(articles, 5) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return render(request, 'index.html', { 'articles': page_obj.object_list, 'paginator': paginator, 'page_number': int(page_number), }) else: articles = '' return render(request, 'index.html', {'articles': articles}) -
How to filter records in complex DB by the fields in related tables?
For example the code /models.py class Tourney(models.Model): tourney = models.CharField() tourney_1 = models.CharField() tourney_2 = models.CharField() class Stage(models.Model): tourney = models.ForeignKey(Tourney, on_delete=models.CASCADE) stage = models.CharField() stage_1 = models.CharField() stage_2 = models.CharField() class Group(models.Model): stage = models.ForeignKey(Stage, on_delete=models.CASCADE) group = models.CharField() group_1 = models.CharField() group_2 = models.CharField() Group has relation on Stage which has relation on Tourney. So now we want to set API for them. Imagine we has serializers for them which include all their fields and called TourneySerializer, StageSerializer and GroupSerializer We want to let possibility to find in all tables the records by the fields in related tables. Actually we would like to search through all of them. /views.py class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = serializers.GroupSerializer def list(self, request, *args, **kwargs): queryset = self.get_queryset() if 'tourney' in request.GET: queryset = queryset.filter(stage__tourney__tourney=request.GET['tourney']) if 'tourney_1' in request.GET: queryset = queryset.filter(stage_tourney_tourney_1=request.GET['tourney_1']) if 'tourney_2' in request.GET: queryset = queryset.filter(stage_tourney_tourney_1=request.GET['tourney_2']) if 'stage_1' in request.GET: queryset = queryset.filter(stage_stage_1=request.GET['stage_1']) if 'stage_2' in request.GET: queryset = queryset.filter(stage_stage_2=request.GET['stage_2']) if 'group' in request.GET: queryset = queryset.filter(group=request.GET['group']) if 'group_1' in request.GET: queryset = queryset.filter(group_1=request.GET['group_1']) if 'group_2' in request.GET: queryset = queryset.filter(group_2=request.GET['group_2']) serializer = self.get_serializer_class()( queryset, many=True) return Response(serializer.data) Here we have one ViewSet with a bunch of obvious … -
Issues with psycopg when installing local requirements.txt
I have tried installing psycopg-binary as some have suggested, but no success. System: Mac 10.15.6 Django3.0.8 Python3.8 ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 -
Static Files Pythonanywhere
When I run python manage.py collectstatic in the bash console I keep getting "python: can't open file 'manage.py': [Errno 2] No such file or directory". But I can clearly see my manage.py file in my code editor, I am a beginner in django and its pretty frustrating. If anyone has any ideas what this can possibly be, I would love your help. Thanks settings.py -
Graphene: "Expected a value of type XXX but received: ..."
I'm using graphene-django to build my API. I have a DjangoObjectType named StoreType which represents the model Store. This model has a MultiSelectField named opening_days that indicates what days in the week the store is open. To create new stores, I use this mutation: class Weekdays(graphene.Enum): MO = "Mo" TU = "Tu" WE = "We" TH = "Th" FR = "Fr" SA = "Sa" SU = "Su" class CreateStore(graphene.Mutation): store = graphene.Field(StoreType) class Arguments: opening_days = graphene.Argument(graphene.List(Weekdays)) def mutate(self, info, opening_days): store = Store(opening_days=opening_days) store.save() return CreateStore(store=store) The mutation works perfectly. But then, when I try to query a store, I get the error "Expected a value of type \"StoreOpeningDays\" but received: Monday, Tuesday", which makes sense really, because this field saves the data as a single string with the values separated by commas. The issue is that graphene is expecting the list specified in graphene.List(Weekdays) which is impossible to retrieve. Any ideas on how to fix this? Thanks in advance! -
Previous form data being applied to Form for editing in django
I have a way for users to edit comments they posted in Django but now Im trying to implement a feature where when users go to edit their comments the previous comment is displayed in the form. This way when a user goes to edit their comment it will show what they said previously in the form field. views.py def update_comment(request, year, month, day, post, comment_id = None ): post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day) comments = post.comments.filter(active=True) comment = Comment.objects.get(id=comment_id) user = request.user comment_form = CommentForm(request.POST, instance=Comment.objects.get(id=comment_id)) if (comment.name != user): raise PermissionDenied if request.method == 'POST': comment_form = CommentForm(request.POST, instance=Comment.objects.get(id=comment_id)) if comment_form.is_valid(): comment_form.instance.post = post comment_form.instance.name = request.user comment_form.save() return HttpResponseRedirect( post.get_absolute_url() ) else: comment_form = CommentForm() return render(request,'posts/update_comment.html', {'post':post , 'comments': comments,'comment_form': comment_form, 'comment_id':comment_id }) urls.py from . import views from django.urls import path, include, re_path from django.contrib.auth import views as auth_views from .views import PostListView, PostCreateView,PostUpdateView app_name = 'posts' urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), #path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.PostDetailView.as_view(),name='post_detail'), path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'), path('post/new/',PostCreateView.as_view(), name='post-create'), path('<int:year>/<int:month>/<int:day>/<slug:post>/update/',PostUpdateView.as_view(), name='post-update'), path('<int:year>/<int:month>/<int:day>/<slug:post>/<comment_id>/',views.update_comment, name='update_comment'), ] update_comment.html {% extends "Main/Base.html" %} {% block content %} <form method="POST" action="{% url 'posts:update_comment' post.publish.year post.publish.month post.publish.day post.slug comment_id %}"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Update comment"></p> </form> {% … -
django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xD9\\x88\\xDB\\x95\\xD8\\xB3...' for column 'name' at row 1")
hi i created a django project and tried to deploy it on ubuntu apache server with mysql database but when i run python3 manage.py migrate i get this error : django.db.utils.OperationalError: (1366, "Incorrect string value: '\xD9\x88\xDB\x95\xD8\xB3...' for column 'name' at row 1") when i run show variables like 'char%'; the output is : +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | latin1 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | latin1 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ and in my /etc/mysql/my.cnf i set [client] default-character-set = utf8 is there something i've missed ?! -
keys must be str, int, float, bool or None, not builtin_function_or_method
This is my cart views, im trying link my products/plans page to this view. Im trying to create an add to cart view so when i click add to cart it will go onto the cart page from django.shortcuts import render, redirect, reverse # Create your views here. def view_cart(request): """ A view that renders the cart page """ return render(request, 'cart/cart.html') def add_to_cart(request, item_id): """ Add plan to shopping cart """ cart = request.session.get('cart', {}) cart[id] = cart.get(id, 1) request.session['cart'] = cart return redirect(reverse('plans')) -
django endpoint not returning all fields specified in serializer
This is Source Def: class SourceDefinition(models.Model): source = models.ForeignKey(Source, on_delete=models.DO_NOTHING) special_id = models.IntegerField(default=0) ad_group = models.CharField(max_length=50) creator = models.CharField(max_length=100) config = JSONField(default=dict, blank=True) class SourceDefinitionSerializer(serializers.ModelSerializer): source = SourceSerializer(read_only=True, many=False) source_id = serializers.PrimaryKeyRelatedField(source="source", queryset=Source.objects.all(), write_only=True) class Meta: model = SourceDefinition fields = '__all__' Engine: class EngineDefinition(models.Model): engine = models.ForeignKey(Engine, on_delete=models.DO_NOTHING) source_def = models.ForeignKey(SourceDefinition, on_delete=models.DO_NOTHING) schedule_def = models.ForeignKey(ScheduleDefinition, on_delete=models.DO_NOTHING, null=True, blank=True) ad_group = models.CharField(max_length=50) creator = models.CharField(max_length=100) where_clause = models.CharField(max_length=1000, null=True, blank=True) config = JSONField(default=dict, blank=True) class EngineDefinitionSerializer(serializers.ModelSerializer): engine = EngineSerializer(read_only=True, many=False) source_def = ScheduleDefinitionSerializer(read_only=True, many=False) schedule_def = SourceDefinitionSerializer(read_only=True, many=False) engine_id = serializers.PrimaryKeyRelatedField(source="engine", queryset=Engine.objects.all(), write_only=True) source_def_id = serializers.PrimaryKeyRelatedField(source="source_def", queryset=SourceDefinition.objects.all(), write_only=True) schedule_def_id = serializers.PrimaryKeyRelatedField(source="schedule_def", queryset=ScheduleDefinition.objects.all(), write_only=True) class Meta: model = EngineDefinition fields = '__all__' Returned value from endpoint using EngineDefinitionSerializer : { "id": 1, "engine": { "id": 1, "name": "en" }, "source_def": { "id": 1, "ad_group": "YYY", "creator": "EEE", "config": {} }, "schedule_def": null, "ad_group": "YYY", "creator": "EEE", "where_clause": null, "config": {} } Why is special_id not being returned in the EngineDefinitionSerializer endpoint response? I also attempted to specify all field names instead of using __all__ and same result occurred. ........... (need more words words worcs words words words wrods)