Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django javascript-catalog missing data from .po file
I am trying to set up a javascript-catalog translation for my project, but to me it seems it is not reading the .po/.mo files My url patterns: urlpatterns = i18n_patterns( .... path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), .... ) I have this header in my template: <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> After checking the source of the rendered template for "Hungarian" language I see a bunch or default translations in the JS catalog file, but not the ones I defined in the .po file: const newcatalog = { "%(sel)s of %(cnt)s selected": [ "%(sel)s/%(cnt)s kijel\u00f6lve", "%(sel)s/%(cnt)s kijel\u00f6lve" ], "6 a.m.": "Reggel 6 \u00f3ra", "6 p.m.": "Este 6 \u00f3ra", "April": "\u00e1prilis", "August": "augusztus", "Available %s": "El\u00e9rhet\u0151 %s", "Cancel": "M\u00e9gsem", "Choose": "V\u00e1laszt\u00e1s", "Choose a Date": "V\u00e1lassza ki a d\u00e1tumot", "Choose a Time": "V\u00e1lassza ki az id\u0151t", "Choose a time": "V\u00e1lassza ki az id\u0151t", "Choose all": "Mindet kijel\u00f6lni", "Chosen %s": "%s kiv\u00e1lasztva", "Click to choose all %s at once.": "Kattintson az \u00f6sszes %s kiv\u00e1laszt\u00e1s\u00e1hoz.", "Click to remove all chosen %s at once.": "Kattintson az \u00f6sszes %s elt\u00e1vol\u00edt\u00e1s\u00e1hoz.", "December": "december", "February": "febru\u00e1r", "Filter": "Sz\u0171r\u0151", "Hide": "Elrejt", ... In my .po file I have: msgid "Routes" msgstr "Utak" Which is compiled into a .mo file, however when … -
Nginx, Django, Gunicorn, working without config file?
I am making a website on django with gunicorn, nginx, on a amazon linux EC2 instance. To deploy the website I use gunicorn --worker-class gevent --bind 0.0.0.0:8000 myapp.wsgi I am using nginx, and everything is working the thing that is weird is that all the static files are working, without me serving them in sudo vi /etc/nginx/nginx.conf. My config file is just the default and its still working. Does django serve static files for you through urls.py in urlpatterns = []+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)... here is my config file # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { 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; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 300; types_hash_max_size 4096; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { listen 80; listen [::]:80; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; … -
Django admin, how to use model to add fields into another
I want to create a class that can be extended by users. I think in something similar to: class User(model.Models): name = models.CharField(max_length=30) class UserAttributes(model.Models): attribute_name = models.CharField(max_length=30) attribute_value = models.CharField(max_length=30) What I want is that when I create an UserAttribute in the admin, it appear in the user admin panel to modify. Ideally, I would don't need to see the attribute value in the UserAttribute form, only in User's one. -
Not able to get flow link in my viewflow application
I'm using viewflow engine in my django project to render the workflow in UI.On running the local server I'm not able to see the "flow" link on left bottom part of the screen which is used to see the graphical representation of workflow.Am I missing any step ? Please help .I can see all the steps of workflow written linearly on dashboard but can't find graphical view of the flow. -
TemplateDoesNotExist atDjango deploy error
Hope, you can help me. I made a django project (just in study) and trying to deploy it with djangogirls tutorial. Okay, it works. But! When i trying to go to my website https://anle93.pythonanywhere.com, I have this: Page not found (404) Request Method: GET Request URL: http://anle93.pythonanywhere.com/ Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ projects/ The empty path didn’t match any of these. It's okay cause I havent any pages in all project. So. When i go to admin, it works(http://anle93.pythonanywhere.com/admin/login/?next=/admin/), I see username and pswd fields. AND when I try to go to my "projects" (https://anle93.pythonanywhere.com/projects/), i have this error first screen on screen. So, my project have this sctructure like on screenscreen2.2. So the question is: I understand, that django cant find base.html file, that extends project_detail.html and project_index.html, and this is the bs4 styles for all project, not for one this app I made, so, if i wonna make any additions like, for example "project_description.html" in new app, it will extends "base.html" too. Ofc, in localhost in works like as needed. I cant understand why it happens after deploy. -
does not exist error in django when trying to delete a user from the admin panel
I am using Django signals I get this type of error when I try to delete a user from the admin panel These is my signal.py file: from django.db.models.signals import post_save, post_delete from django.contrib.auth.models import User from .models import Profile def createProfile(sender, instance, created, **kwargs): print("Profile signal triggered") if created: user = instance profile = Profile.objects.create( user=user, username=user.username, email=user.email, name=user.first_name, ) def deleteUser(sender, instance, **kwargs): user = instance.user user.delete() post_save.connect(createProfile, sender=User) post_delete.connect(deleteUser, sender=Profile) and here is my models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) short_intro = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_image = models.ImageField( null=True, blank=True, upload_to="profiles/", default="profiles/user-default.png", ) social_github = models.URLField( blank=True, null=True, validators=[validate_url_github] ) social_twitter = models.CharField( max_length=200, blank=True, null=True, validators=[validate_url_twitter] ) social_linkedin = models.CharField( max_length=200, blank=True, null=True, validators=[validate_url_linkedin] ) social_youtube = models.CharField( max_length=200, blank=True, null=True, validators=[validate_url_yt] ) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False ) def __str__(self): return str(self.username) and here is my app.py file from django.apps import AppConfig class UsersConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'users' def ready(self): import users.signals Please answer why do … -
403 Forbidden - Apache2
when Im typing my DomainName witout www at the beginning, I have SSL certificate and everything is Ok. When Im going with www.(DomainName.com) or putting my elastic IP from AWS im facing: 403 Forbidden You don't have permission to access this resource. Where should I look for the issu.. sites-available, permisions sudo chown :www-data ~/myproject? -
docker container with django gunicorn nginx
I am trying to dockerize django using gunicorn and nginx into a docker image. Running docker-compose up --detach --build Everything builds successfully. But gunicorn is not starting. Error log says: bash: /home/soccer/venv/bin/gunicorn: /Users/Umar/PycharmProjects/soccer/venv/bin/python: bad interpreter: No such file or directory How can I fix this? Dockerfile: # pull official base image FROM python:3.7 # accept arguments ARG PIP_REQUIREMENTS=production.txt # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip setuptools # create user for the Django project RUN useradd -ms /bin/bash soccer # set current user USER soccer # set work directory WORKDIR /home/soccer # create and activate virtual environment RUN python3 -m venv venv # copy and install pip requirements COPY --chown=soccer ./requirements /home/soccer/requirements/ RUN pip3 install -r /home/soccer/requirements/${PIP_REQUIREMENTS} # copy Django project files COPY --chown=soccer . /home/soccer/ docker-compose.yml: version: "3.8" services: nginx: image: nginx:latest ports: - "80:80" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/home/soccer/static - media_volume:/home/soccer/media depends_on: - gunicorn gunicorn: build: context: . args: PIP_REQUIREMENTS: "${PIP_REQUIREMENTS}" command: bash -c "/home/soccer/venv/bin/gunicorn --workers 3 --bind 0.0.0.0:8000 soccer.wsgi:application" depends_on: - db volumes: - static_volume:/home/soccer/static - media_volume:/home/soccer/media expose: - "8000" environment: DJANGO_SETTINGS_MODULE: "${DJANGO_SETTINGS_MODULE}" DJANGO_SECRET_KEY: "${DJANGO_SECRET_KEY}" DATABASE_NAME: "${DATABASE_NAME}" DATABASE_USER: "${DATABASE_USER}" DATABASE_PASSWORD: "${DATABASE_PASSWORD}" db: image: postgres:latest restart: always environment: … -
How to get a random element of the filtered queryset efficiently?
I try to pull a random object from the already filtered queryset this way: Product.objects.filter(active=True).order_by('?').first() Currently it is solved with .order_by('?') but it seems to be very slow. I try to implement the solution of this question to my view. It does not work so I am not sure if I am doing it the right way. products = Product.objects.filter( active=True, ) count = products.aggregate(count=Count('id'))['count'] random_index = randint(0, count - 1) product = products[random_index] This is my code now and it throws the ValueError: ValueError: low >= high Please, help me to speed it up. -
How do u solve django.db.utils.OperationalError: fe_sendauth: no password supplied when you are creating a django super user
django.db.utils.OperationalError: fe_sendauth: no password supplied DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sobs', 'USER': 'ahmed', 'PASS': str(os.environ.get("PASS")), 'HOST': 'localhost' } } -
Django Serializer always returns the value as null when accessing with foreign key
In models.py class ExamplePublication(models.Model): name=models.CharField(max_length=20) class Meta: managed = False db_table = 'xxx' class ExampleBook(models.Model): publication = models.ForeignKey(ExamplePublication, models.DO_NOTHING, related_name='egpublication') title = models.CharField(max_length=20) class Meta: managed = False db_table = 'xxx' class Example(models.Model): book = models.ForeignKey(ExampleBook, models.DO_NOTHING, related_name='egbook') author = models.ForeignKey(ExampleAuthor, models.DO_NOTHING, related_name='egauthor') city = models.CharField(max_length=20) class Meta: managed = False db_table = 'xxx' In serializer.py, class ExampleSerializer(serializers.ModelSerializer): publicationname = serializers.ReadOnlyField(source='book.publication.name',read_only=True) class Meta: model = Example fields = ('city','publicationname') Here the publicationname always returning null I could not find the exact reason or Is my approach wrong with using foreign keys. Any help would be fine :) Thanks -
How to properly write a Django view for a Patch request
So I am making a view in Django, and I'm trying to use POST for creation, GET for fetching, I wanted to use PATCH for handling updations, but I am struggling to understand how to process an incoming PATCH request's data. I am sending a PATCH request in POSTMAN, with form-data(key-value pairs), but when trying to access the data, request.POST or request.PATCH or request.data dont work. Only thing that works is request.body which is a byte string that I have to decode and I don't want to do something like that just to access the data, is there a better way to do this? My question is, what is the right way to make a PATCH view and how to handle the data from an incoming request? Handling POST data seems so straightforward by doing request.POST, why is PATCH not as straightforward? What do i do? Should I not be using PATCH then? Is it better to use POST for updation as well? -
DRF : How to edit the default URLs generated by SimpleRouter?
I have a viewset as : class UserViewset(mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): ... Router for this viewset is as : router = routers.SimpleRouter() router.register(r'(?P<uid>[^/.]+)/user', views.UserViewset) For the RetrieveModelMixin, I want to use this 'uid' parameter as in the url for retreiving the object, not the 'pk' parameter that DRF automatically appends to the URL. How can this be done ? -
Django-Haystack is not able to fetch the data in template .txt file
Below are my files. My issue is the print statement within index_queryset() prints all the record, but nothing is shown on the front-end. It says "No Result Found" for all the queries. models.py class Jobs(models.Model): ID = models.CharField(primary_key = True, max_length = 50) JOB_TITLE = models.TextField(db_index=True) JOB_COMPANY = models.TextField() JOB_LOCATION = models.TextField(db_index=True) JOB_SALARY = models.CharField(max_length= 200,null=True) search_indexes.py from haystack import indexes from .models import Jobs class JobIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) type = indexes.CharField(model_attr='JOB_TITLE') location = indexes.CharField(model_attr='JOB_LOCATION') def get_model(self): return Jobs def index_queryset(self,using=None): print(self.get_model().objects.all()) # prints all the objects return self.get_model().objects.all() search.html {% extends 'base.html' %} {% block content %} <h2>Searching</h2> <form method="get" action="."> <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td> <input type="submit" value="Search"> </td> </tr> </table> {% if query %} <h3>Results</h3> {% for result in object__list %} <p> <a href="{{ result.object.get_absolute_url }}">{{ result.object.JOB_TITLE }}</a> </p> {% empty %} <p>No results found.</p> {% endfor %} <p>"PAGE": {{ page.object_list }} </p> {% if page.has_previous or page.has_next %} <div> {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %} | {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %} </div> {% endif %} {% else %} … -
Access denied in DRF testing even thought user has permission
I grant my test user all permissions and I still get acces denied response when testing. Everything works in production. I am using DjangoObjectPermissions in my permission classes. Deleting DjangoObjectPermissions results in granting permission in testing. Both delete and patch tests are failing. views.py class DeventDetailAPIView( generics.RetrieveAPIView, mixins.UpdateModelMixin, mixins.DestroyModelMixin): permission_classes = [permissions.IsAuthenticated, permissions.DjangoObjectPermissions] serializer_class = CalendarSerializer queryset = Devent.objects.all() def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) def patch(self, request, *args, **kwargs): day = Day.objects.get(date__iexact=request.data['day']).pk request.data['day'] = day return self.update(request, *args, **kwargs) test_api.py class TestDeventAPIView(APITestCase): @classmethod def setUpTestData(cls): cls.test_user1 = User.objects.create_user( username='testuser1', password='1X<ISRUkw+tuK') newgroup = Group.objects.create(name='testgroup') for each in Permission.objects.all(): newgroup.permissions.add(each) cls.test_user1.groups.add(newgroup) ( test data creation omitted from post) def test_patch_gets_pk(self): user = self.test_user1 token = get_token(user) data = { 'day':'2020-01-20', 'title':'test devent patch', 'description':'test description' } request = self.factory.patch( '/calendar/api/devent/1/', data, HTTP_AUTHORIZATION='JWT ' + token, format='json') view = DeventDetailAPIView.as_view() response = view(request, pk = 1) response.render() print(json.loads(response.content)) prints {'detail': 'You do not have permission to perform this action.'} -
How to find migrations of external installed django apps?
Given a number of external Django apps that I use in INSTALLED_APPS, I need to restore the whole db. I don't understand how I could access migrations folders for these external apps. Is there a way to find these migrations folders or to completely cancel all the made migrations? -
Get total played time with React Player
I am working on a video subscription site using Django and React. As we will have multiple people who want to make content for us, I would like to be able to track the time a user has spent in any video, then update the database by adding that time when the page is left. This is in order to know how much each video has contributed to our revenue. I am currently using React player to play videos, but I can easily transition to other type of player. Also, if anyone has a better way to track the time without using any player, I would appreciate any answer. <ReactPlayer url={this.state.lectie.link} controls type="video/mp4" /> -
Django how to pass context which inside if statement? [closed]
I getting this error Django local variable referenced before assignment def Count_Notifications(request): count_notifications_author = 0 if request.user.is_authenticated: commnet_user = BlogComment.objects.filter(user=request.user) if request.user == commnet_user: count_notifications_comment= 0 count_notifications_comment = Notifications.objects.filter(sender=request.user,is_seen=False).count() count_notifications_author = Notifications.objects.filter(user=request.user,is_seen_author_noti=False).count() return {'count_notifications_comment':count_notifications_comment,'count_notifications_author':count_notifications_author} If add count_notifications_comment= 0 at the beginning then the error gone but actual count not showing in template. it's just showing 0 in my template: def Count_Notifications(request): count_notifications_comment= 0 count_notifications_author = 0 how to solve this problem??? how to pass the count_notifications_comment to template which inside my if statement? -
Customizing serializer response in django rest framework
I want to change the response format. I have my models as: class A(models.Model): a = models.ForeignKey(ab, blank=True, null=True, on_delete=models.CASCADE) b = models.ForeignKey(bc, blank=True, null=True, on_delete=models.CASCADE) My serializers.py class ASerializer(serializers.ModelSerializer): add = MymodelSerializer() #model bc serializer class Meta: model = A fields = ('id', 'add') class BASerializer(serializers.ModelSerializer): add= serializers.SerializerMethodField() def get_add(self, obj): b_id = A.objects.filter(a=obj.id) serializer = ASerializer(b_id, many=True) return serializer.data class Meta: model = ab My view is returning data as this: { "id": 2, "add": [ { "add": { "key":"value" } }, } ] }, I want it to be : { "id": 2, "add": [ { "key":"value" }, { "key":"value" }, } ] }, Where should the code be changed so that the ouput will be as above. -
How to implement change password modal form?
I have implemented authentification using Django django.contrib.auth and it work but I would like change_password to be displayed using modal form and Ajax. And I do not manage to even display the form inside modal (with all validation stuff). I have already use bootstrap modal to display information but not for form submission. As it did not call a change_password view that render change_password_form.html template, form is not available and I got an error Parameter "form" should contain a valid Django Form. How should I do this? urls.py class PasswordChangeView(SuccessMessageMixin, auth_views.PasswordChangeView): success_message = "Your password have been changed successfully." def get_success_url(self): return reverse('export:index') app_name = 'registration' urlpatterns = [ ... path('change_password/', PasswordChangeView.as_view(), name='password_change'), ... ] password_change_form.html {% extends 'layouts/base.html' %} {% load bootstrap4 %} {% load crispy_forms_tags %} {% load i18n %} {% block title %}{% trans 'Change password' %}{% endblock %} {% block content %} <div class="row justify-content-center" style="margin-top:100px;margin-left:0px;margin-right:0px"> <div class='col-6'> <div class='card' > <div style="background-color:#326690;padding:5px 5px 5px 16px;color:white;font-weight:bold;border-radius: 2px 2px 0 0;">Change password</div> <div class='card-body' style="padding-bottom:0px"> <form method="post" class="form-signin"> {% csrf_token %} {% bootstrap_form form layout="horizontal" placeholder="None" size="medium" label_class="form-label col-md-3" %} </div><hr style="margin:1px"> <div class='card-body' style="padding-top:5px;padding-bottom:5px;"> <div> <button type="submit" class="btn block" style="float:right;background-color:#326690;color:white;min-width:110px;">{% trans 'Confirm' %}</button> <a href="{% url … -
what is the best way to filter result in modelviewset per user?
I am creating an api with Django rest framework. I use only ModelViewsSet. I need the result of some viewset to be different depending on the user who makes the request. For the moment I have overloaded the get_query_set method for each ModelViewSet. This works very well, depending on the user the results are different for the "list" and also for the "read" which returns a 404 if the user tries to access an element he doesn't have the right to. def get_queryset(self): if self.request.user.is_staff: return cache.get_or_set( 'machine_machines_list', Machine.objects.all() \ .select_related('category') \ .prefetch_related('machine_stock') \ .prefetch_related('components'), 60) else: return cache.get_or_set( f'machine_machines_list_user_{self.request.user.pk}', Machine.objects.filter(site__user=self.request.user)\ .select_related('category') \ .prefetch_related('machine_stock') \ .prefetch_related('components'), 60) However I'm not sure if this is the best method or if it is really secure. Is it the right method? Or is there a better way to do it? -
sort data per datetime (python, django)
I am trying to sort my operation by date. The data is formed of couple columns similarly to the one drawn here: Company Income datetime X 520305 03.06.2020 11:20:00 Y 480305 06.06.2020 13:20:00 In my case for example, if the user inputs a start date of 10.05.2020 00:00:00 til 05.06.2020 10:00:00. the expected output would be only X. I hope I am being clear, sorry in advance if I am confusing. Here is what I did so far: def home(request): if request.method == 'POST': file = request.FILES['myFile'] csv = pd.read_csv(file) StartDate = request.POST.get('startdate') EndDate = request.POST.get('enddate') user_start = pd.to_datetime(StartDate) user_end = pd.to_datetime(EndDate) csv['Date'] = pd.to_datetime(csv['Date'], dayfirst=True) montant_init = csv.groupby("Initiateur")["Montant (centimes)"].sum() err_count = csv.groupby(['Résultat']).size() return render(request, "index.html", {'something': True, 'montant': montant_init, 'error': err_count}) html: {% if something %} <label for="startdate">Start Date (y.m.d h.m.s):</label> <input type="text" name="startdate"><br><br> <label for="enddate">End Date (y.m.d h.m.s):</label> <input type="text" name="enddate"><br><br> <input type="submit" name="submit"> <p>{{ montant }}</p> <p>{{ error }}</p> thank you -
Why is my post request is flagged as unauthorized when using AllowAny permission class
I have a request which take POST headers only and I have used the permission_classes([AllowAny]) decorator as below: @api_view(["POST"]) @permission_classes([AllowAny]) def endpoint(request): print(request.data) return Response({"status": "success"}, status=status.HTTP_200_OK) and have also tried switching order of decorators: @permission_classes([AllowAny]) @api_view(["POST"]) def endpoint(request): print(request.data) return Response({"status": "success"}, status=status.HTTP_200_OK) However whenever I make the request it is blocked as unauthorized. I have also tried to make the request crsf_excempt and that responds with - WSGIRequest object has no attribute 'data'. I am running on django 2.2.5 -
remove 'this field is required' text above django form
I cannot remove bullet points saying 'this field is required' above my django form (see picture). I have been through other questions and tried setting form.auto_id = False, form.use_required_attribute = False and form.label_suffix = "" I am not sure what attribute of the form is causing this to appear so don't know what to change. I couldn't find the answer in the docs here the .view function is def new_page(request): if request.method == "POST": form = WikiSubmitForm(request.POST) if form.is_valid(): # data cleaning? Title = form.cleaned_data["Title"] Body = form.cleaned_data["Body"] if Title in util.list_entries(): return HttpResponse("This wiki page already exists") else: util.save_entry(title=Title, content=Body) return HttpResponseRedirect("wiki/"+ Title) #would be better to make this not hardcoded! else: form = WikiSubmitForm(request.POST) # form.use_required_attribute = False return render(request, "encyclopedia/new_or_edit_page.html", { "new": True, "form": form }) The HTML file, called new_or_edit_page.html is: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1> {% if new %} <h1>New page</h1> {% else %} <h1>Edit page for {{ Title }}</h1> {% endif %} </h1> {% if new %} <form action="{% url 'new_page' %}", method="POST"> {% else %} <form action="{% url 'edit' Title %}", method="POST"> {% endif %} {% csrf_token %} <div> {{ form … -
Django select_related Not Working as Expected
I have 2 classes, Country and Coordinates. When making an API call to the Country table, I would like the API (using DRF) to return the related Coordinate information as well. By default, the following is understandably returned (localhost:8000/api/country/): { "id": 1, "name": "TestCountry", "coordinates": 1 } The problem is that after implementing select_related in my views.py file, and modifying the CountrySerializer as well, the output remains exactly the same. I had expected something like: { "id": 1, "name": "TestCountry", "coordinates": { "longitude": 123, "latitude": 456, } } Or even this would suffice: { "id": 1, "name": "TestCountry", "longitude": 123, "latitude": 456, } And here are the relevant code in models, views, and serializer files. class Coordinates(models.Model): longitude = models.DecimalField() latitude = models.DecimalField() class Country(models.Model): name = models.CharField() coordinatesID = models.ForeignKey(Coordinates, on_delete=models.SET_NULL, verbose_name="Coordinates", db_column="CoordinatesID", blank=True, null=True, related_name="coordinates") class CountryViewSet(viewsets.ReadOnlyModelViewSet): queryset = Country.objects.select_related('coordinatesID').all() serializer_class = CountrySerializer class CountrySerializer(DynamicFieldModelSerializer): longitude = serializers.ReadOnlyField(source='coordinates.longitude') latitude = serializers.ReadOnlyField(source='coordinates.latitude') class Meta: model = Country fields = '__all__' Additionally, in the Country table, I specified the related_name="coordinates", however select_related does not recognize this option, and I still have to use "coordinatesID" to reference the coordinate table. Is this a bug or related to incorrect implementation?