Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Django to reference the name instead of the id/pk
I am currently working on a tutoring API using Python and Django. I want the Tutor Model to show all the tutees (yes, that is a word) and the tutee to show the tutor. Right now, it works correctly but it references the id/pk of the model so I really don't know who or what it refers to. GET a tutee : { "id": 1 "full_name": "First Last", "email": "email@emailprovidercom", "tutor": 1, "subjects": "SubjectX" } As you can see, the tutor is a number instead of a name. GET a tutor: { "id": 1, "full_name": "First Last", "email": "name.name@emailprovider.com", "notes": "XXXXX XX XX X X X X X X XXXXXX XX X X X X ", "tutees": [ 1 ] } The same thing happens here. I am using Django Rest Framework. My models class Tutor(models.Model): full_name = models.CharField(max_length=40) email = models.EmailField() notes = models.TextField() def __str__(self): return self.full_name class Tutee(models.Model): full_name = models.CharField(max_length=40) email = models.EmailField() tutor = models.ForeignKey(Tutor, on_delete=models.CASCADE, related_name="tutees") subjects = models.CharField(max_length=13) def __str__(self): return self.full_name My Serializers class TutorSerializer(serializers.ModelSerializer): class Meta: model = Tutor fields = ['id', 'full_name', 'email', 'notes', 'tutees'] class TuteeSerializer(serializers.ModelSerializer): class Meta: model = Tutee fields = ['id', 'full_name', 'email', "tutor", "subjects"] My … -
Can ImportExportModelAdmin update with django?
I'm still new to Django and found this cool plugin for django called ImportExportModelAdmin that allows me to upload excel files into my DB. However I can't find anything on it updating. Does anybody know if you can update with this plugin or no? -
How to get all objects from many to many relation?
So i have 2 models: class Artist(models.Model): """Artist model.""" name = models.CharField('Artist name', max_length=255) genre = models.CharField('Music genre', max_length=255) class Event(models.Model): """Event model.""" name = models.CharField('Event name', max_length=255) description = models.TextField('Description') localization_name = models.CharField('Localization name', max_length=255) longitude = models.FloatField('Longitude', default=0.0) latitude = models.FloatField('Latitude', default=0.0) artists = models.ManyToManyField(Artist, verbose_name='Artists') date = models.DateTimeField('Event date') And i need to get for one artist, every other artist that was with him on events. I made this on Artist model: @property def get_participate_artists(self): return list(self.event_set.all().values_list('artists__event__artists__name', 'artists__event__artists__genre', named=True).distinct()) but i wanna get queryset or list of Artist objects. -
Stack objects in columns in HTML
I have a list of words that I want to stack in columns in order to save and use the left place in an html file for a Django project: I tried to use the <div class="col-lg-4 col-md-6"> tag but without success ... so how do you stack objects in columns in HTML? {% extends "todo/base.html" %} {% block content %} <!-- Header --> <header class="intro-header"> <div class="container"> <div class="col-lg-5 mr-auto order-lg-2"> <h3><br>Tell me something about you... </h3> </div> </div> </header> <!-- Page Content --> <section class="content-section-a"> <div class="container"> <dt> <span>Pick the keywords you want to express when wearing perfume</span> </dt> <div class="row"> <div class="col-lg-5 mr-auto order-lg-2"> <div class="recommendations"> <form action = "/getmatch" method="POST"> {% for keyword in keywords %} <div class="col-lg-4 col-md-6"> <h3>{{ keyword.title }}</h3> </div> {% endfor %} {% csrf_token %} <button type="submit">Envoyer</button> </form> </div> </div> <!-- /.container --> </div> </div> </section> <!-- Bootstrap core JavaScript --> <script src="static/vendor/jquery/jquery.min.js"></script> <script src="static/vendor/popper/popper.min.js"></script> <script src="static/vendor/bootstrap/js/bootstrap.min.js"></script> {% endblock %} I am aiming at making a multiselection based on buttons or images that would be these words. -
How to send data present in html table rows to back end
Im trying to make a simple library management app using django . I don't know how to send data present in html table rows to backend for storing into database I know I can use json but I think there is more sofesticated way ... This is the code please help I appreciate that... {% extends 'home.html' %} {% block b %} <div class="container"> <table class="table"> <thead> <tr> <th scope="col">book_name</th> <th scope="col">writer_name</th> <th scope="col">category</th> <th scope="col">Sub_category</th> <th scope="col">price</th> <th scope="col">quntity</th> </tr> </thead> <tbody id="table"> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> <td>123</td> <td>1w3</td> </tr> </tbody> </table> <input type="button" class="btn btn-primary" value="store"/> </div> <hr /> <div class="container"> {{ form}} <input type="button" class="btn btn-primary" value="orderd" id="orderd" /> </div> -
Why won't the urls.py file in my Django project let me import this file?
I'm trying to import a function from a file in another directory into my urls.py file. I have included the directory in the settings.py file, ran the ./manage.py makemigrations & the ./manage.py migrate Django commands, and imported the function and the file into the urls.py file. Here is my current code: urls.py: from django.contrib import admin from django.urls import path from apps.accounts.urls import account_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += accounts_urlpatterns settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'rest_framework', 'rest_framework.authtoken', 'djoser', # 'apps.accounts' ] apps/accounts/urls.py: from django.conf.urls import url, include accounts_urlpatterns = [ url(r'^api/v1/', include('djoser.urls')), url(r'^api/v1/', include('djoser.urls.authtoken')), ] the error message: ImportError: cannot import name 'account_urlpatterns' from 'apps.accounts.urls' (/Users/{name}/programming/dj/backend/server/apps/accounts/urls.py) and the project structure: . └── server ├── apps │ └── accounts │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py └── server ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py I appreciate any advice - thank you in advance! -
how to change list to order by username instead of random in Django [duplicate]
I'm having a problem with django views.py , How can i change the "my_users" variable to an ordered list instead of a random list. I'd like to order it by username. This may be simple but i'm still new to Django, thanks. @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) sent_to = [] friends = [] for user in users: friend = user.friends.all() for f in friend: if f in friends: friend = friend.exclude(user=f.user) friends+=friend my_friends = request.user.profile.friends.all() for i in my_friends: if i in friends: friends.remove(i) if request.user.profile in friends: friends.remove(request.user.profile) **my_users = random.sample(list(users), min(len(list(users)), 10))** for r in my_users: if r in friends: my_users.remove(r) friends+=my_users for i in my_friends: if i in friends: friends.remove(i) for se in sent_friend_requests: sent_to.append(se.to_user) context = { 'users': friends, 'sent': sent_to } return render(request, "users/users_list.html", context) -
using cpanel for django apps
Sorry if this question is off-topic, but I need to know if cPanel is really a good choice for hosting Django apps. Currently, my Django app has various packages and some of them need to be compiled, but I don't have superuser privileges to enable or install compilers. Should I still use cPanel or look for other Django friendly alternatives. -
How to create chart in HTML using pychartjs
I am new to web development and I wanted to create a chart on HTML page. In my search I found https://github.com/IridiumIO/pyChart.js repository where I can create charts in python. I followed instructions in readme file but I am missing something. Any leads could help me. I am not sure where am I doing it wrong. Please note that I am not a web developer : Installed pycharm and created a python project installed pyChartjs using pip created a home.html file with following script: <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script> </head> <body> <canvas id="myChart"></canvas> <script> var data = {{ chartJSON | safe }} var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, data); </script> </body> </html> created a python file plot.py with following script: class MyBarGraph(BaseChart): type = ChartType.Bar class data: label = "Numbers" data = [12, 19, 3, 17, 10] backgroundColor = Color.Green def homepage(request): NewChart = MyBarGraph() NewChart.data.label = "My Favourite Numbers" # can change data after creation ChartJSON = NewChart.get() return render(request=request, template_name='home.html', context={"chartJSON": ChartJSON}) -
Can a django url contain a fixed path at the beginning?
I have a server running a django application. This version is stable. For testing purposes I want to host a testing version of the same application on the server. Normally you could do this with subdomains, so the stable version runs at myserver.de and the testing version at test.myserver.de. This is not possible for me, I have only one available domain (myserver.de). So I can only use paths. Let's say I host the stable version at myserver.de/[apps urls] and the test version at myserver.de/test/[apps urls]. To achieve this, i could edit all urls in the testing version. But that would defeat the purpose of testing, because to then make a testing version stable, i would have to re-edit all urls. So I would love to simply edit settings.py and put ALLOWED_HOSTS = ["mysite.de/test"] for the testing version. I tested this locally with ALLOWED_HOSTS = ["127.0.0.1:8000/test", "127.0.0.1/test"], but that unsurprisingly didn't work (I read the docs ^^) Is there a way to run two applications on a django server where the urls of one app always start with /test/<rest> without editing all urls? Could I do this with apache2 instead? (My guess was no, because django builds all links in the … -
Django redirection to react front end causing issue after OAuth2 authentication
I'm trying to implement OAuth2 authentication for the React and Django project. In the development environment (local machine) react will be running on localhost:3000 and Django/DRF will be running on localhost:8000 This is how my flow looks, Kindly excuse if the flow is not easy to grasp. But I will try to explain better below I have 4-5 Django apps all of them have their own functionalities. The user app will have a custom user model and user info related logic. OAuth2 app will have authentication related logics. So this is how my flow works. Step 1: User will access react app by navigating to localhost:3000 or domain name. On the component mount, react will try to get the user information by calling an API endpoint i.e. to the user app API endpoint. Step 2: Since the user is accessing the app for the first time and the user is not logged in, the django user app will send back 403 unauthorized access error to the react app. Step 3: Now react will catch that 403 error and tries to login the user. It makes an API call to the Django OAuth app endpoint and gets the OAuth (Azure AD) … -
Updating a django view with values from a js addin: How to trigger a change event and pass the values back to the view
I've got a form that has a dropdown for selecting the reporting period with the finish always being the current day and start determined by the dropdown selection of week, month, quarter or year. When the period form updates, it has an on change event that submits the form, the page recalculates with the new start date and refreshes. I want to replace this with something more precise and I've got xdsoft's period picker http://xdsoft.net/jqplugins/periodpicker/ partly working but not actually doing anything except logging the change in the console! The period picker is picking up the start and end values on loading and when I update the period dropdown form, displaying those dates as correctly, but when I want to refine that selection by editing the range in the periodpicker, I don't know how to trigger an on change event to recalculate the view similarly to the period form which uses a fieldwrapper onchange to do it. Once this is working, I'll eliminate the period form dropdown as it won't be required but at the moment, it's the only way I could get the values in there so I can pull some data for different periods. Simply put, I need … -
Comment Reply button is not clicking in Django, Json
I am making a Blog app and I built a Comment and Comment Reply Feature BUT that is not working. views.py def create_reply(request,pk): comment = get_object_or_404(Comment,pk=pk) reply = Reply(description=request.GET.get('description'),comment=comment,user=request.user) reply.save() return JsonResponse({'reply':model_to_dict(reply)}) models.py class Reply(models.Model): description = models.TextField() date = models.DateTimeField(auto_now_add=True) comment = models.ForeignKey(Comment,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f'[User] {self.user} [Comment] {self.comment.comment_body[:30]}' detail.html {% for comment in comments %} <div class="comment"> <p class="info"> {{ comment.created_at|naturaltime }} {{ topic.post_owner }} </p> {{ comment.comment_body|linebreaks }} <a class="btn btn-info btn-circle" href="#" id="addReply{{comment.id}}"><span class="glyphicon glyphicon-share-alt"></span> Reply</a> <a class="btn btn-warning btn-circle" data-toggle="collapse" href="#replyOne" id="showReplies{{comment.id}}"><span class="glyphicon glyphicon-comment"></span>{{comment.reply_set.count}} Replies</a> <script> document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { $('#showReplies{{comment.id}}').click(function (event) { event.preventDefault(); $('#replyList{{comment.id}}').slideToggle() }) $('#replyForm{{comment.id}}').slideToggle() $('#addReply{{comment.id}}').click(function (event) { event.preventDefault(); $('#replyForm{{comment.id}}').slideToggle() $('#showReplies{{comment.id}}').click() }) $('#cancelCommentReply{{comment.id}}').click(function (event) { event.preventDefault; $('#replyForm{{comment.id}}').toggle(); $('#commentReplyInput{{comment.id}}').val('') }) $('#replyForm{{comment.id}}').submit(function (event) { event.preventDefault(); $.ajax({ url: "{% url 'create_reply' comment.id %}", data: { 'description': $( '#commentReplyInput{{comment.id}}' ) .val(), }, dataType: 'json', success: function (response) { $.ajax({ url: "{% url 'get_user_by_id' %}", data: { 'pk': response .reply .user, }, method: 'get', dataType: 'json', async: false, success: function ( userResponse ) { let user = userResponse .user $('#replyList{{comment.id}}') .prepend(` <li class="media media-replied"> <a href="/people/${user.id}"> <img src="${user.avatar}" alt="User Image" width="64" height="64"> </a> <div class="media-body"> <div class="well well-lg"> <h4 class="media-heading … -
Why Python pytz package has both Asia/Kolkata and Asia/Calcutta timezones?
I was working on a dropdown with list of all timezones and I took the list of timezones from Python pytz package. I noticed that Asia/Kolkata and Asia/Calcutta both appear in the list where as Asia/Calcutta has been renamed to Asia/Kolkata. Is there a reason pytz is not removing the older timezone? -
Django - caching queryset result
For each of my 12 views I have a few commun querysets currently duplicated in each view. I'm wondering If there is a way to cache the result to avoid recalculating everytime (querysets are differents for each user but once it's set it's barely never change) Company_user = Company.objects.get(User = request.user) User_info = User_info.objects.get(User = request.user) Groups_user = request.user.groups.values_list('name',flat = True) Sales_company = Sales.objects.filter(Company = Company_user) I have also few forms repeted in each views (bootstrap modal open by clicking in a navbar button) Change Password Change personal infos Change sales target Change personnal informations Change target Is there a way to optimize this ? -
Communicating between two Django applications
I have two DjangoREST applications, ServiceA and ServiceB running on different servers. I am using RabbitMQ as my broker and want the two services to commnicate, I assume the producer ServiceA is sending the message. but following the code in the rabbitmq documention it keeps the connection open and it interacts with my Django server on ServiceB. Here is what i have ServiceA def partial_update(self, request, pk=None, *args, **kwargs): email = request.auth.get('email') user = am.AppUser.objects.get(user=email) serializer = aps.AppUserSerializer(user, data=request.data, partial=True) data = { "email": request.auth.get('email') } if serializer.is_valid(): serializer.save() data.update(request.data) message = json.dumps(data) connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='rpc_queue') channel.basic_publish(exchange='', routing_key='test_key', body=message) connection.close() return Response(serializer.data, status=status.HTTP_206_PARTIAL_CONTENT) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ServiceB class RpcClient(object): connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='rpc_queue') def get_user_data(ch, method, props, body): body = body.decode("utf-8") try: x = json.loads(body) queryset = am.AppUser.objects.filter(user=x.get('email')) serializer = aps.AppUserSerializer(queryset, data=x, partial=True) if serializer.is_valid(): serializer.save() ch.basic_publish(exchange='', routing_key="rpc_queue", properties=pika.BasicProperties(correlation_id=props.correlation_id), body=json.dumps(body)) ch.basic_ack(delivery_tag=method.delivery_tag) except Exception as e: print(str(e)) channel.basic_qos(prefetch_count=4) channel.basic_consume(queue='rpc_queue', on_message_callback=get_user_data) print("[x] Awaiting RPC requests") channel.start_consuming() What am I getting wrong? -
SQL Alchemy connection refused when trying to connect db and web containers
I am having problem when running docker-compose up with my django/postgres app(using sqlalchemy). Everything is fine when just running it localy but when i try to contenerise it(with Docker) I am having an error sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused. Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? For some reason app is not connecting to db. My docker-compose.yml: version: "3.9" services: db: image: postgres:9.6 environment: - POSTGRES_DB=my database - POSTGRES_USER=my user - POSTGRES_PASSWORD=my password web: build: . command: python3 manage.py runserver 127.0.0.1:8080 volumes: - .:/code ports: - "8080:8080" depends_on: - db My Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip3 install --trusted-host pypi.python.org -r requirements.txt COPY . /code/ My engine: engine = create_engine("postgresql://mu user:my password@127.0.0.1:5432/my database") Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my database', 'USER': 'my user', 'PASSWORD': 'my password', 'HOST': '127.0.0.1', 'PORT': 5432, } } Can anyone advice where am I making mistake? -
getting error in graphene-django during running tests [ GraphqlTestCase class ]
i write some tests using GraphQlTestCase for my graphene-django api : from graphene_django.utils.testing import GraphQLTestCase class ProductsQueryTestCase(GraphQLTestCase): GRAPHQL_URL = "/graphql" def test_product_by_name_query(self): """ the productByName query given a required arguments named 'name' and return the product with given name """ response = self.query( ''' query productByName($input: String!) { productByName(name: $input) { id name } } ''', op_name="productByName", # Related to the data entered in the database [this is product with id=1] variables={"input": "Marble Floors"} ) self.assertResponseNoErrors(response) but unfortunately i receive an error : { "errors": [ {"message":"Product matching query does not exist."} ] } anybody can help me in this issue or anything about writing tests for graphene-django apis ? -
Django Pass Input to URL
I want to make a search field in django. I have a database with books and want, that the user can write e.g. "3" in a field and than the URL should look like this: www.url.com/search/3 3 is the id How can I do that? btw. I already have this: www.url.com/book/3 but I want, that the user writes it in a input field :) -
Django Mttp how to access element of Jquery nestable
I've been trying to access Html Element with Jquery. I have nested category in Django and I want to update the parent of the menu with drag and drop. enter image description here HTML <div class="dd" id="nestable3"> {% load mptt_tags %} <ol class="dd-list" > {% recursetree menu %} <li class="dd-item dd3-item" data-id="{{ node.id }}" data-parent="{{node.parent.name}}" id="nestable-item"> <div class="dd-handle dd3-handle" ></div> <div class="dd3-content" id="nestedList">{{ node.name }}</div> {% if not node.is_leaf_node %} <ol class="dd-list" > {{ children }} </ol> {% endif %} </li> {% endrecursetree %} </ol> JQUERY $('.dd').nestable().on('change', function(e) { /* It should be write data-id and parent id */ }); -
How to save a form in a database (django)
I have a quiz. I have 2 pages, I create the questions and their answers on the first page and I put these questions on the second page, but I want these questions to have the Answer model input, i.e. each question has its own input. When I try to set a query with an Id in the view and the unsuitable Answer form to save does not work, it is not stored in the database. How do I save? models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question import random def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm questions=Question.objects.all() if request.method=="POST": instance=Question.objects.get(id=request.POST['i_id']) print(instance) form=AnswerForm(request.POST, instance=instance) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, … -
gunicorn: error: unrecognized arguments: myproject.wsgi:application
I am trying to deploy my django project. I am trying to use gunicorn and Nginx. While following this tutorial. I reached at setting up the gunicorn.service file at location /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=tk-lpt-0098 Group=www-data WorkingDirectory=/home/tk-lpt-0098/Desktop/myproject/myproject ExecStart=/usr/bin/gunicorn /usr/share/man/man1/gunicorn.1.gz --workers 3 --bind unix:/etc/systemd/system/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target Proceeding further, I then run the following two commands sudo systemctl start gunicorn sudo systemctl enable gunicorn Now by checking the status of the server using command sudo systemctl status gunicorn I am experiencing the following error gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2021-01-21 19:20:03 PKT; 38s ago Main PID: 967938 (code=exited, status=2) جنوری 21 19:20:03 noc-HP-ProBook-650-G1 systemd[1]: Started gunicorn daemon. جنوری 21 19:20:03 noc-HP-ProBook-650-G1 gunicorn[967938]: usage: gunicorn [OPTIONS] [APP_MODULE] جنوری 21 19:20:03 noc-HP-ProBook-650-G1 gunicorn[967938]: gunicorn: error: unrecognized arguments: myproject.wsgi جنوری 21 19:20:03 noc-HP-ProBook-650-G1 systemd[1]: gunicorn.service: Main process exited, code=exited, status=2/INVALIDARGUMENT جنوری 21 19:20:03 noc-HP-ProBook-650-G1 systemd[1]: gunicorn.service: Failed with result 'exit-code'. I am using ubuntu version Ubuntu 20.04.1 LTS I have tried changing working directory but did not work. I would really appreciate if anyone can help me out with this issue. -
How can I set up an SSL configuration in Namecheap for Angular deployed on GitHub Pages and Django deployed on App Engine
I am deploying my system, Angular frontend using GitHub and the whole backend in the Google Cloud Platform - App Engine, SQL, Elasticsearch etc. Https seems to be working properly between website and the client as I have checked in the GitHub settings Enforce HTTPS. However I am not sure whether I do a correct configuration between Angular app and my Django API which is deployed in the App Engine. Can anyone take a look at the configuration and confirm that everything is done correctly? I would like to do everything as safely as possible. User portal should be accessible from example.com and www.example.com and the Django API on App Engine from api.example.com and www.api.example.com. Besides maybe you have any additional safety tips or advice on what else I could do to increase protection? Namecheap: Google App Engine: -
How can I use an external API to authenticate user's login instead of Django's inbuilt authentication system?
I'm currently working as an intern in a company. I'm helping to create a software using Django for their company to use. This software requires login system. However, their company have an API endpoint which logins a user using user's email and password and returns an access token upon successful login. How can I make use of the API to login the user? I've tried to search online but couldn't find any solution to it. -
Different ordering fields for ViewSets actions
I have a viewset lets say TestingViewSet which has a default ordering field id. class TestingViewSet(viewsets.ReadOnlyViewSet): ordering = ('id',) But there as some custom action views that uses the super(TestingViewSet).list that i want to change the ordering field for them conditionally e.x def distinct_list(self, request): return super(TestingViewSet, self).list(request) Is there a way like to change the ordering field of function distinct_list only?