Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.Abstract BaseUser'>. Was __classcell__ propagated
Getting this error while trying to migrate databases after manually setting up postGREsql database for the project. Was trying to run the cloned quora project forked from github when this error cropped up. FULL ERROR DESCRIPTION:- RuntimeError: __class__ not set defining 'AbstractBaseUser' as . Was __classcell__ propagated to type.__new__? Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\core\management\__init__.py", line 327, in execute django.setup() File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\user\Desktop\quora-clone-master\env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\user\Desktop\quora-clone-master\env\lib\site-packages\django\contrib\auth\base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? -
Allow End User To Add To Model, Form, and Template Django
Is there anything that someone could point me towards (a package, an example, a strategy, etc) of how I could implement the ability for an end user of my app to create a new field in a model, then add that model field to a model form and template? I’m thinking of the way that Salesforce allows users to add Custom fields. I don’t really have any start point here I am only looking to learn if/how this might be possible in Django. Thanks! -
Using Django for incoming Streaming API?
We would like to implement a connection to a streaming API and store the continuously incoming information in a relational database. There will be roughly 50,000 database inserts per day. We prefer to implement this in Django. In short, we will create a service that establishes a GET connection to a server and this connection never closes. However, is Django suited for these purposes? In other words, where should this service best be implemented in Django, because it does not contain a view. Likewise, how does Django deal with these concurrent activities? Wouldn't this service block the Django app from doing anything else? Thanks! -
Django model not working in admin section on Heroku
I want to deploy a new model on my heroku app, for making comments in my blog app. For this, I created a new class 'Comment' in models.py and added it it also to admin.py. Then i migrated it locally: manage.py makemigrations manage.py migrate Next i uploaded it to heroku: git add -A git commit "add model" git push heroku master and migrated it there: heroku run python manage.py migrate But then it gives me following message: psycopg2.errors.UndefinedTable: table 'blog_comment' does not exist I tried to use the hint heroku run python manage.py migrate --fake It seems that with this it will create the model and show it in the admin section. But when I click on 'Comment' there, it will just give out "Error 500". So it is not possible for me to access the Comment model. On my local computer it all works without a problem, but on heroku I think i forgot something. Can anyone help? Best regards -
how specify the that the model information get only selected model
i have four model shop , products, customer,order how arrange them so that shop as user if the customer search the shop category then list of shop present and when he select the shop then the products of the shop present and he place order and fill his information then shop get the customer information and product details he have order -
Cant install Django-admin >> cl.exe error failed with exit status 2
I am trying to install django-admin but run into the following error: C:\Users\Jonas\Desktop\CFD\CFD>pip install django-admin Collecting django-admin Using cached django_admin-2.0.1-py2.py3-none-any.whl (7.6 kB) Collecting django-excel-response2>=3.0.0 Using cached django_excel_response2-3.0.2-py2.py3-none-any.whl (4.4 kB) Collecting django-excel-base>=1.0.4 Using cached django_excel_base-1.0.4-py2.py3-none-any.whl (4.0 kB) Requirement already satisfied: django-six>=1.0.4 in c:\users\jonas\appdata\local\programs\python\python38-32\lib\site-packages (from django-excel-response2>=3.0.0->django-admin) (1.0.4) Collecting screen Using cached screen-1.0.1.tar.gz (8.6 kB) Requirement already satisfied: xlwt in c:\users\jonas\appdata\local\programs\python\python38-32\lib\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (1.3.0) Requirement already satisfied: pytz in c:\users\jonas\appdata\local\programs\python\python38-32\lib\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (2019.3) Building wheels for collected packages: screen Building wheel for screen (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\jonas\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Jonas\\AppData\\Local\\Temp\\pip-install-qzvcu9nl\\screen\\setup.py'"'"'; __file__='"'"'C:\\Users\\Jonas\\AppDat a\\Local\\Temp\\pip-install-qzvcu9nl\\screen\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Jonas\AppData\Local \Temp\pip-wheel-oenuazzg' cwd: C:\Users\Jonas\AppData\Local\Temp\pip-install-qzvcu9nl\screen\ Complete output (19 lines): running bdist_wheel The [wheel] section is deprecated. Use [bdist_wheel] instead. running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\screen copying screen\compat.py -> build\lib.win32-3.8\screen copying screen\old_str_util.py -> build\lib.win32-3.8\screen copying screen\__init__.py -> build\lib.win32-3.8\screen running build_ext building 'screen.str_util' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\source C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\users\jonas\appdata\local\programs\python\python38-32\include -Ic:\users\jonas\appdata\local\programs\python\p ython38-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\include" /Tcsource/str_util.c /Fobuild\temp.win32-3.8\Release\source/str_util.obj str_util.c c:\users\jonas\appdata\local\programs\python\python38-32\include\pyconfig.h(59): fatal error C1083: Datei (Include) kann nicht ge”ffnet werden: "io.h": No such file or … -
Can anyone explain this django model?
I trying to learn django. I am trying to understand slug and collected few lines of code which generates url with pk & title text. It works fine but cann't understand everything. Can anyone give me a little explanation of this one? class ArticlePkAndSlug(models.Model): title = models.CharField(max_length=settings.BLOG_TITLE_MAX_LENGTH) slug = models.SlugField(default="", editable=False, max_length=settings.BLOG_TITLE_MAX_LENGTH) def get_absolute_url(self): kwargs = {"pk": self.id, "slug": self.slug} return reverse("article-pk-slug-detail", kwargs=kwargs) def save(self, *args, **kwargs): value = self.title self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) -
How to make a dynamic countdown timer using django and javascript?
From views.py I am returning date and time to my HTML page. But unable to use that date and time to set a countdown timer using Javascript For e.g return render(request,'page.html',{'date':i.date,'time':i.time,'hours':i.hours}) time represents starting time hours represent total countdown time 'i' is python object -
Using multiple POST requests with different urls in a single page
I am trying to build a todo-list with an add/delete and completed button for each todo. I've used multiple forms and POST requests to make it work. Is there a better solution to achieve this? Current issues- page refresh after adding adds the same item to the list, page refresh after every request. views.py from django.shortcuts import render, redirect from .models import * from .forms import ListForm # Create your views here. def homePage(request): list = List.objects.all() form = ListForm() if request.method == 'POST': form = ListForm(request.POST) if form.is_valid(): form.save() context = {'list': list, 'form': form} return render(request,'todoList/home.html',context) def deleteList(request,pk): list = List.objects.get(id=pk) if request.method == 'POST': list.delete() return redirect('/') def completed(request,pk): list = List.objects.get(id=pk) if request.method == 'POST': print(list.completed) if list.completed == False: list.completed = True else: list.completed = False list.save() return redirect('/') Html <h2>Todo list</h2> {% for listItem in list %} <div class="row"> <form class="bottomCont" action=" {% url 'delete_list' listItem.id %} " method="POST"> {% csrf_token %} <div class="col-sm-3"> <h4>{{ listItem }}</h2> </div> <div class="col-sm-1"> <p>{{ listItem.completed }}</p> </div> <div class="col-sm-2"> <p>{{ listItem.date_added }}</p> </div> <div class="col-sm-1"> <button type="submit" class="btn btn-danger">Delete</button> </div> </form> </div> <form action=" {% url 'completed' listItem.id %}" method="POST"> {% csrf_token %} <div class="col-sm-1"> <button type="submit" … -
Why is Django not saving to database?
I believe I have the correct code, but when I submit the form, nothing is saved to the database. I have debugged the code and the data from the form is being sent via POST, it' just that nothing is being saved to the database: views.py def sign_up_post(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user) if p_form.is_valid(): user_object = p_form.save() user_object.save() return redirect('sign_in_photo_verify') else: p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'p_form': p_form } return render(request, 'users/sign-up-post.html', context) forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image', 'city', 'state', 'zip', ] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( default='default.jpg', verbose_name='Profile Image', max_length=255, storage=FileSystemStorage(location=UPLOAD_DIR, base_url='/media/uploads/')) verification_image = models.ImageField( default=None, null=True, blank=True, verbose_name='Verification Image', max_length=255, storage=FileSystemStorage(location=UPLOAD_DIR, base_url='/media/uploads/')) city = models.CharField(max_length=30, null=True) state = models.CharField(max_length=2, null=True) zip = models.CharField(max_length=5, null=True) approved = models.BooleanField(default=False) def is_approved(self): return self.approved def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): return super(Profile, self).save(*args, **kwargs) def verification_image_tag(self): from django.utils.html import escape from django.utils.html import mark_safe return mark_safe('<img src="%s" />' % escape(self.verification_image.url)) verification_image_tag.short_description = 'Verification Image' verification_image_tag.allow_tags = True -
I can not display bookmarks for the user (django)
I'm trying to make the function of adding and displaying bookmarks (favorites) of the user. I do the guide. What is at the moment: User bookmarks are successfully added successfully to the database I can not display the bookmarks that the user added Below I attach the code that adds a bookmark for the user. models.py Article Model: class Post(models.Model): title = models.CharField(max_length=200, unique=True,) slug = models.SlugField(max_length=200, unique=True,) content = RichTextUploadingField() def get_bookmark_count(self): return self.bookmarkarticle_set.all().count() # def __str__(self): return self.title Abstract model: class BookmarkBase(models.Model): class Meta: abstract = True user = models.ForeignKey(User, verbose_name="user") def __str__(self): return self.user.username Inherited Model: class BookmarkArticle(BookmarkBase): class Meta: db_table = "bookmark_article" obj = models.ForeignKey(Post, verbose_name="article") views.py class BookmarkView(View): model = None def post(self, request, pk): user = auth.get_user(request) bookmark, created = self.model.objects.get_or_create(user=user, obj_id=pk) if not created: bookmark.delete() return HttpResponse( json.dumps({ "result": created, "count": self.model.objects.filter(obj_id=pk).count() }), content_type="application/json" ) I'm trying to display bookmarks in the template that the user added: {% for bookmark in user.bookmarkarticle_set.all %} {{ bookmark.post.title }} {% endfor %} Nothing is output. What needs to be done to display the bookmarks that the user has added? I would be grateful for any help. Bookmarked guide source -
Django messages not showing up instead showing <django.contrib.messages.storage.session.SessionStorage object at 0x0000029C6456A388>
Django messages not showing up instead showing . I have tried every solution given at StackOverflow by other users but it;s not working. import os INSTALLED_APPS = [ 'crispy_forms', 'login.apps.LoginConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' -
Bulk upload of files in the admin site
Django 3.0.6 I have a model with multiple ImageFields. Could you tell me how to bulk upload them? I have tried django-bulk-admin, but it doesn't work with Django 3.0. Could you help me find such a ready made app? If it is not possible, what is the easiest solution? -
Django urls.py: passing dynamic url parameter into include()
I found in Django docs (https://docs.djangoproject.com/en/3.0/topics/http/urls/#passing-extra-options-to-include) that I can pass any constant into include() statement. Here in docs' example we are passing blog_id=3. from django.urls import include, path urlpatterns = [ path('blog/', include('inner'), {'blog_id': 3}), ] But what if I want to pass dynamic url parameter into include()? I mean something like this: from django.urls import include, path urlpatterns = [ path('blog/<int:blog_id>/', include('inner'), {'blog_id': ???}), ] Is it possible? -
Any Better Way to get the Print Result For Django Model
Any Better Way to Write This Code For Django Model A few subtleties that are worth mentioning: class Model_a(models.Model): a_Name = models.CharField(max_length=200, null=True, blank=True) a_city = models.CharField(max_length=200, null=True, blank=True) a_address = models.CharField(max_length=200, null=True, blank=True) class Model_b(models.Model): Model_a= models.ForeignKey(Model_a, on_delete=models.CASCADE,null=False) b_pin = models.CharField(max_length=200, null=True, blank=True) b_zip = models.CharField(max_length=200, null=True, blank=True) b_distance = models.CharField(max_length=200, null=True, blank=True) qs = Model_a.objects.filter( model_b__b_pin='11', a_city ='101') for i in qs: for b in i.model_b_set.all(): print(b.b_zip + "------" + i.a_city)``` -
How can I get the ID for formset form that's generating error?
I have the following tags in my html template so that I can view formset errors. Is there any way of getting the id number of the formset that is generating the error? <div class="alert alert-warning" role="alert"> {{formset.errors}} </div> <div class="alert alert-warning" role="alert"> {% for dict in formset.errors %} {% for error in dict.values %} {{ error }} {{ dict.key }} {% endfor %} {% endfor %} </div> At the moment I get the following, and as I'm doing something complex with the formsets I can't match the errors to forms in the formset: -
Mirror/inherit a module for outputting some fields of the original
Is it possible, in Django, to create a module which is linked via a OneToOneField to another one, which only outputs a single field of its parent? Something like: class Venue(models.Model): # this is the parent venue_name = models.CharField(max_length=50) venue_city = models.CharField(max_length=50) venue_country = models.CharField(max_length=50) class VenueCity(models.Model): # should this be (Venue)? venue_city = # this is the OneToOneField linked to the venue_city field of the parent I need this because it'd be very handy for using it with a select2 field ( django_select2 - limit the returned text to a specific field in module) and I cannot use a @property, only a proper module. -
Unique value error without unique parameter
I'm trying to be able to create Accounts with usernames unique for each Server class Server(models.Model): name = models.CharField(primary_key=True, max_length=50, unique=True) class Account(models.Model): server = models.ForeignKey(Server,on_delete=models.CASCADE) username = models.CharField(max_length=100) account_name = models.CharField(max_length=100) password = models.CharField(max_length=50) right now I'm getting the duplicate key value violates unique constraint "zuya_aaccount_username_5f0a17d4_uniq" When I create a non-unique account_name it doesn't show any problem -
Django Rest FrameWork: Combining data from different models before sending response
I have a default user model I created a userprofile model as shown below. from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from users.utils.age_validator import MinAgeValidator from django.core.validators import MaxValueValidator, MinValueValidator class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile_number = models.IntegerField(blank=True, unique=True, null=True) profile_image = models.ImageField(upload_to="proile_image", blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) There is a search view written as shown below class FindUser(ListAPIView): permission_classes = [IsAuthenticated] search_fields = ['username', 'first_name', 'last_name'] queryset = User.objects.all() serializer_class = FindUserSerializer filter_backends = (filters.SearchFilter,) pagination_class = SearchLimitPagination Then I defined serializers to combine data from both models. class UserProfileImageSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('profile_image',) read_only_fields = ['profile_image'] class FindUserSerializer(serializers.ModelSerializer): image = UserProfileImageSerializer(read_only=True) class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name','image') The question is similar to the this(Django REST Framework and combining models). But this is not working for me. It is not giving error but a response without the profile data as shown below. { "count": 11, "next": "http://127.0.0.1:8000/user/userprofile/finduser/?limit=5&offset=5&search=a", "previous": null, "results": [ { "id": 43, "username": "pikachu", "first_name": "", "last_name": "" }, } Iam using django 2.7 -
Using Django + MongoDB with unstructured data
I've boradly seen Django used together with MongoDB (with modules like djongo) with structured data using Models. This conflicts one of my requirements: being able to store data in an unstructured way (missing fields, nested objects ...) since the usage of Django Models enforces the specification of all document fields. I thought of encapsulating all the required DB calls in a DAO object but it sounds a bit alien in the Django scene. -
save inputs from 2 forms, through one view into 2 tables django
I am new to django and wanted to know if it is possible to save inputs from 2 forms (displayed on the same html page) into 2 different models through 1 view. Currently, only the first form saves to the table. Form 2 is ignored. If there is anything missing or incorrect, please explain so I understand what my errors are. Here is my View: class SubmitChoiceView(TemplateView): template_name = 'test/test_page1.html' def get(self, request): form1 = SubmitChoiceForm() form2 = SubmitMethodForm() return render(request, self.template_name, {'form1': form1, 'form2': form2}) def post(self, request): form1 = SubmitChoiceForm(request.POST) form2 = SubmitMethodForm(request.POST) if form1.is_valid(): post = form1.save(commit=False) post.user = request.user post.save() if form2.is_valid(): post2 = form2.save(commit=False) post2.user = request.user post.save() return redirect('home') args = {'form1': form1, 'form2': form2} return render(request, self.template_name, args) -
Selectable table with django
My mission here is to add a checkbox in first <td>, so I can select the rows I want and only export those to csv. I got the export function working and everything, but I can't figure out how to sort so it's only those I check, who will be exported. They as well needs to change a boolean from False to True when they've been exported. Let's therefore say, to keep it simple, that I'd like to do X with the chosen rows and change a boolean, on a button click. I got a table looking like this: <table id="example" class="display" style="width:100%"> {% for shipment in object_list %} <tr role="row" class="odd"> <td class="sorting_1">{{ shipment.increment_id }}</td> <td>{{ shipment.full_name }}</td> <td>{{ shipment.street }}</td> <td>{{ shipment.zip_code }}</td> <td>{{ shipment.city }}</td> <td>{{ shipment.telephone }}</td> <td>{{ shipment.email }}</td> <td>{{ shipment.products }}</td> <td>{{ shipment.lost_because_of }}</td> <td>{{ shipment.custom_comment }}</td> <td>{{ shipment.date }}</td> </tr> {% endfor %} </table> My views.py is as following: class ShipmentList(LoginRequiredMixin, ListView): html_title = 'All Shipments' page_title = 'All Shipments' login_url = '/log-in/' redirect_field_name = 'accounts:log_in' model = models.NewShipment paginate_by = 100 # if pagination is desired template_name = 'shipment-list.html' How can I make this happen based on a ListView? Further related code … -
AttributeError: module 'urllib.request' has no attribute 'user'
I am trying to create article so i need to request the current user's information. user = User.objects.get(id=request.user.id) profile = Profile.objects.filter(user=user).get() instance = profile It gives me this error while trying to do it: File "C:\...app\views.py", line 41, in aRTİCLECreateView user = User.objects.get(id=request.user.id) AttributeError: module 'urllib.request' has no attribute 'user' -
AWS S3 Rejects API Call with HTTP 400
I am following this tutorial on getting Django to upload files to AWS S3 asynchronously. The problem is that I am getting this message back from the call that actually uploads the file (the other two come back HTTP 200). <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> The first hunch was to set AWS_S3_SIGNATURE_VERSION = "s3v4" in the settings.py, but that was both futile and superfluous since the version of Boto supports only this signature and so does the region of the AWS. In case you are wondering, the policyData JSON looks roughly as follows: { file_bucket_path: "videos/25/" file_id: 25 filename: "25.mov" key: <key-here> policy: "CnsiZXhwaXJhdGlvbiI6IjIwMjEtMDEtMDFUMDA6MDA6MDBaIiwKImNvbmRpdGlvbnMiOlsKeyJidWNrZXQiOiJ6ZHJhdm9zdC13ZWItZXVyb3BlLXRlc3QifSwKWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJ2aWRlb3MvMjUvIl0sCnsiYWNsIjoicHJpdmF0ZSJ9LAoKWyJzdGFydHMtd2l0aCIsIiRDb250ZW50LVR5cGUiLCIiXSwKWyJzdGFydHMtd2l0aCIsIiRmaWxlbmFtZSIsIiJdLApbImNvbnRlbnQtbGVuZ3RoLXJhbmdlIiwwLDUyNDI4ODAwMF0KXQp9Cg==" signature: "qECJMNncmLNF6pMKBAQRQa64O3M=" url: "https://<bucket-name-here>.s3-eu-central-1.amazonaws.com/" username: "email@test.com" <prototype>: {…} } The following are the views: import base64 import hashlib import hmac import os import time from rest_framework import permissions, status, authentication from rest_framework.response import Response from rest_framework.views import APIView from django.conf import settings from .models import FileItem class FilePolicyAPI(APIView): """ This view is to get the AWS Upload Policy for our s3 bucket. What we do here is first create a FileItem object instance in our Django backend. This is to include … -
how to get distance in drf api reponse?
I have exactly the same problem as this SO question (Sorry for the link and not writing the whole content again.) Also, I have already implemented the solution given for the same problem. but I am not getting distance in API response. I haven't added distance in serializer fields so definitely, it won't show up in response. But when I add it to fields I get following error. Field name distance is not valid for model Address. I also tried to write a serializer method field but was not sure how to pass the location received in query params to the serializer for comparison. So the question is how the distance is supposed to send in API response?