Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Python Django App Deployment Failure: No module named 'oauth2_provider'
I am following the Django OAuth Toolkit tutorial. I have the app running successfully on my local server with Django OAuth Toolkit installed. When I try to deploy to Heroku I get a "ModuleNotFoundError: No module named 'oauth2_provider'" error while running '$ python manage.py collectstatic --noinput'. I have attempted to search Stack Overflow for similar questions but was unable to find one. I saw many questions on Stack Overflow relating to collectstatic but I do not think that is my problem. My backtrace is as so: remote: -----> Python app detected remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 27, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 94, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 978, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 961, in _find_and_load remote: File "<frozen … -
I need to create a lot of lists of songs based only on their owners, i have 2 models and ForeignKey
I need to create lists of songs based on artists: My models: class Band(models.Model): photo = models.ImageField( blank=True, verbose_name=_("Picture"), null=True) band_name = models.CharField( max_length=256, blank=False, verbose_name=_("Artist")) notes = models.TextField( blank=True, verbose_name=_("Extra notes")) song = models.ManyToManyField('Lyrics', blank=True, verbose_name=_("Song")) class Meta(object): verbose_name = _("Artist") verbose_name_plural = _("Artists") def __str__(self): return self.band_name class Lyrics(models.Model): song_name = models.CharField( max_length=256, blank=False, verbose_name=_("Song name")) song_lyrics = models.TextField( blank=False, verbose_name=_("Lyrics")) artist = models.ForeignKey('Band', verbose_name=_("Artist"), # related_name="songs", blank=False, null=True, on_delete=models.PROTECT) class Meta(object): verbose_name = _("Song") verbose_name_plural = _("Songs") def __str__(self): if self.artist: return u'{} {}'.format(self.song_name, self.artist.band_name) else: return u'{}'.format(self.song_name) Right now I have lists with songs of all artists, but i need to to have lists of songs based on artists who created them I can't manage it for 2 weeks, help me please -
Auto Increment non-pk field starting at 1000
I have been working in Django for about a week now so I don't have much idea on the following. I need to create a sequence for a field in my model and postgres database that auto increments starting at 1000. So it would list like: 1000, 1001, 1002, etc.... From what I have researched so far I would need to extend the save function and check the previous value in the db. The end result is to be able to post to an API using this model and this field increments like above. class MyModel(AuditMixin, models.Model): order_number = models.IntegerField(blank=False) def get_number(self): return ??? def save(self): ??? .save() -
How to let user create a page via a URL?
I am thinking along the lines of /mysite/blogs/new. I know about add_child and about Routablepage, also the 'permissions route' but I still don't see how to permit page creation via a URL. I am surprised that there do not appear to be any instructions for doing this, as relying on the admin method surely isn't acceptable for many 'naive' users. Indeed, it took me a while to realise that Wagtail isn't like Wordpress, in the sense of having an 'Add Post' button or the like. The documentation does not clearly state that users are (apparently) expected to create pages via the Admin section either. In fact, there seems to be an assumption that developers will be familiar with Django, even though a CMS ought to be easier to use IMO. Just to be clear, I think that Wagtail is great but the instructions leave something to be desired. Perhaps I will attempt to update them myself! -
Change username max_length in Django 1.11 (django.contrib.auth)
My users are using e-mail addresses as usernames, which caused a problem in Django 1.9 because there was a 30 character maximum username length. This was supposed to be fixed by Django 1.10, with a 150 character limit, I believe (though it looks like the docs actually say that max_length should be able to go up to 191 characters for certain databases). I upgraded to Django 1.11 but username still seems to be limited to 30 characters. Is it because I need to set the value of max_length somewhere? If so, where do I set this (an example would be great)? If not, how do I increase the max length? Here is my current view. def register(request): alreadyRegistered = False invalidID = False context_dict = {} if request.method == 'POST': # Gather the username and password provided by the user. # This information is obtained from the login form. Userid = request.POST['username'] Userid = Userid[0:29] # horrible work-around that has to change if User.objects.filter(username=Userid).count() > 0: alreadyRegistered = True else: isGU = 1 > 0 # this will always = TRUE for now if isGU or isEA: firstname = request.POST['firstname'] lastname = request.POST['lastname'] email = Userid password = request.POST['password'] user … -
handling EMAIL_HOST_PASSWORD in Django
I had created an application in Django,for which I had implemented an email service.It was working fine, but now,I have to deploy the application to a server(Heroku). Now,for configuring email service with django,certain attributes are added in the settings.py file like EMAIL_HOST_PASSWORD,EMAIL_BACKEND.... My concern is reagarding the EMAIL_HOST_PASSWORD attribute,can this also be deployed?Will there be any security concerns regarding this attribute? -
Django custom admin template access GET parameters
I want to create custom django admin template and pass there some data. Is it possible to access GET query in custom template ? -
Django model field with default value from another model
I have a model like this: class ModelA(models.Model): foo = models.CharField(max_length=255) bar = models.CharField(max_length=255) Now i wanna have something like this: class ModelB(models.Model): aaa = models.ForeignKey(ModelA) tar = models.Char(Field(max_length=255, default="") fo2 = models.CharField(max_length=255, default=???) where i want fo2 to take a value from ModelA unless other is provided. How should i do that? -
How can i login Android app with (Django) CSRF?
i make login for my application. But, i need CRSF token for login in app. First, i try send a cookie and get a csrf. But i am beginner and it doesn't work. Actually, i don't know what i make. I use this app cross my web site. And i use django for web site and API(Django Rest Framework) for android app. private static final String KEY_LOGIN = "http://192.168.1.102:8080/api-auth/login/"; private static final String KEY_CSRF = "csrf"; public static final String KEY_EMAIL = "email"; public static final String KEY_PASSWORD = "password"; CookieManager cookieManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextPassword = (EditText) findViewById(R.id.editTextPassword); } private void loginUser() { final HttpCookie cookie = new HttpCookie("lang", "tr"); try { cookieManager.getCookieStore().add(new URI("http://192.168.1.102:8080/api-auth/login/"), cookie); } catch (URISyntaxException e) { e.printStackTrace(); } final String email = editTextEmail.getText().toString().trim(); final String password = editTextPassword.getText().toString().trim(); StringRequest stringRequest = new StringRequest(Request.Method.POST,KEY_LOGIN,new Response.Listener<String>() { @Override public void onResponse(String response) { if(response.contains("is_admin")) { openProfileCompany();} else { openProfileUser(); }}}, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(Home.this,error.toString(),Toast.LENGTH_LONG).show(); } }){ public String csrf; @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String,String>(); params.put(KEY_EMAIL,email); params.put(KEY_PASSWORD,password); params.put(KEY_CSRF,csrf); return params; } }; -
Publishing my first Django app
I'm trying to get my first django web app online and I've followed this tutorial (https://www.youtube.com/watch?v=Y-CT_l1dnVU&t=305s), both the video and text tutorial closely. I've looked up other tutorials but I keep getting the same results, "502 Bad Gateway nginx/1.4.6 (Ubuntu)". If someone can tell me what i'm doing wrong, that would honestly make my day. I've been at this for a couple days now. I am using django 1.10.5 and python 3.6. I can supply any other information needed for aid. If there are other tutorials that you recommend, that would be appreciated as well. Thanks you, in advance! -
RequestFactory & reverse with pk (must be called with either an object pk or a slug)
So I have this code: request = self.factory.get(reverse('portal-edit-automation', args=(self.rule.id,))) And if I set a pdb break point right before it and do: (Pdb) reverse('portal-edit-automation', args=(self.rule.id,)) u'/portal/automations/edit/1/' I get the expected response. So why am I getting this when running the test suite? AttributeError: Generic detail view EditAutomation must be called with either an object pk or a slug. -
Django Admin override displayed field value
I have following model: class Model(models.Model): creator = models.ForeignKey(User,related_name='com_creator',on_delete=models.SET_NULL, blank=True, null=True) username = models.CharField(max_length=60,default="") created = models.DateTimeField(auto_now_add=True) body = models.TextField(max_length=10000,default=" ") subtype = models.CharField(_("SubType"),max_length=100) typ = models.CharField(_("Type"),max_length=50) plus = models.ManyToManyField(User,related_name='com_plus', verbose_name=_('Plus'), blank=True) is_anonymous = models.BooleanField(_('Stay Anonymous'), blank=True, default=False) The values in typ and subtype are codes, like: "6_0_p", (because the original values are ridiculosly long, so I use codes and a dict to translate to human readable form). QUESTION: How can I intercept these values in django admin and translate them to human readable form? This is what i tried so far: class ModelAdmin(admin.ModelAdmin): model = Model extra = 1 exclude = ("username","creator","plus" ) readonly_fields = ('subtype','typ','is_anonymous','created') fields = ('body','subtype','typ') def typ(self, obj): self.typ = "ppp" obj.typ = "ppp" return "pppp" I tried returning the object, self, some other value. I also tried to set the value without using a callable just declaring "typ='xxx'". Nothing. I probably don't understand how this whole thing works ... Any ideas will be appreciated. -
Hosting Public websites with Django Dev Server
I am trying to host my personal website, I am new to hosting websites business, so this may be a Noob question. So I made my website using django, and tested everything locally. Now I want to make the site public, then I came across this : https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment which seemed to be a pain in the arse. But, Then I figured i could make the website available on all interfaces using: python manage.py runserver 0.0.0.0:80 Now I can access the website using http://myIp/myapp So my question is, "Is it a good idea to host websites using the django dev server" The gut feeling is a "No", but I really want to know "Why?" -
Restricting a Counter Collection in Python
I am currently extracting data from a web API and I am trying to filter some values based on the following condition: Count the number of times that a user appears between two given dates but only if he/she has bought items raspberry pi, banana pi and raspberry pi2 and not item raspberry pi3 The JSON object that I receive has the following structure: [{ user_id : 0001 CreatedOn: "2017-02-16 15:54:48", item: "raspbery pi", VIP: "YES", Vendor_CODE: "XYZ12345", }, { user_id : 0001 CreatedOn: "2017-02-15 13:49:16", item: "raspbery pi2", VIP: "YES", Vendor_CODE: "XYZ67890", }, { user_id : 0001 CreatedOn: "2017-02-10 15:54:48", item: "raspbery pi", VIP: "YES", Vendor_CODE: "RST171820", }, { user_id : 0001 CreatedOn: "2017-01-01 21:51:13", item: "raspbery pi3", VIP: "YES", Vendor_CODE: "XOL002321", }, { user_id : 0005 CreatedOn: "2017-01-30 17:34:18", item: "raspbery pi", VIP: "YES", Vendor_CODE: "RST171820", }, { user_id : 0005 CreatedOn: "2017-05-30 09:04:08", item: "banana pi", VIP: "YES", Vendor_CODE: "ITI342027", }] Currently I have the following code that counts the number of times a user appears given two dates. from django.shortcuts import render from django.http import JsonResponse from rest_framework.views import APIView from rest_framework.response import Response from collections import Counter from datetime import datetime, timedelta import json, urllib.request, … -
Django-messages integrated reply form
I'm currently working on adding django-messages to my website:https://github.com/arneb/django-messages I've got everything working well and looking good with bootstrap however im struggling to get my view.html working in the way i want it to. Currently you see the messages like this: this is the code in view.html {% extends "django_messages/base.html" %} {% load i18n %} {% block content %} <h1>{% trans "View Message" %}</h1> <dl class="message-headers"> <dt>{% trans "Subject" %}</dt> <dd><strong>{{ message.subject }}</strong></dd> <dt>{% trans "Sender" %}</dt> <dd>{{ message.sender }}</dd> <dt>{% trans "Date" %} </dt> <dd>{{ message.sent_at|date:_("DATETIME_FORMAT")}}</dd> <dt>{% trans "Recipient" %}</dt> <dd>{{ message.recipient }}</dd> </dl> {{ message.body|linebreaksbr }}<br /><br /> {% ifequal message.recipient.pk user.pk %} <a href="{% url 'messages_reply' message.id %}">{% trans "Reply" %}</a> {% endifequal %} <a href="{% url 'messages_delete' message.id %}">{% trans "Delete" %}</a> {% comment %}Example reply_form integration {% if reply_form %} <h1>{% trans "Compose reply"%}</h1> <form action="{% url 'messages_reply' message.id %}" method="post"> {% csrf_token %} <table> {{ reply_form.as_table }} </table> <input type="submit" value="{% trans "Send" %} &raquo;"/> </form> {% endif %} {% endcomment %} {% endblock %} How to i add this into a sort of chat box? i really have no idea how to do this as im very new to django and web development … -
Django wsgi Apache2: 'AH01630: client denied by server configuration'
I've followed this tutorial to deploy my django project : https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-debian-8 Why the static files can't be loaded from apache? I am using Debian9, Python3.5 and Django 1.11 This is my virtual host configuration: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/alex/djangoproject/static <Directory /home/alex/djangoproject/static> Require all granted </Directory> <Directory /home/alex/djangoproject/cpanel> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djangoproject python-home=/home/alex/djangoproject/djangoprojectenv python-path=/home/alex/djangoproject WSGIProcessGroup djangoproject WSGIScriptAlias / /home/alex/djangoproject/cpanel/wsgi.py </VirtualHost> ` And the apache error from error.log: AH01630: client denied by server configuration /home/alex/djangoproject/static And my settings.py config related to static foder STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') -
Images not showing up for django-simple-captcha
I am using django-simple-captcha to make a captcha for different contact buttons on a webpage. I think I have it all working except for the fact that the images for the captcha won't show up. urls.py: from django.conf.urls import url from django.conf.urls import include from . import views urlpatterns = [ url(r'^$', views.product_landing, name='product_landing'), url(r'(?P<product_slug>.*)/?$', views.product_detail, name='product_detail'),url(r'^captcha/', include('captcha.urls')) ] html for page: </form> {% else %} {% if is_valid %} <div style="margin-top: 70px; margin-bottom: 200px;"> <h1 style="margin-bottom: 25px">Thank you!</h1> <p style="font-size: 17px; line-height: 32px;;">Your resume has been received and we will be in touch with a decision soon. Please contact us if you have any questions.</p> </div> {% else %} <form action="" method="POST" id="apply-form" enctype="multipart/form-data" class="application-form"> {% csrf_token %} <div class="firstname {% if form.first_name.errors %}form-error{% endif %}"> <p>FIRST NAME</p> {{ form.first_name }} </div> <div class="lastname {% if form.last_name.errors %}form-error{% endif %}"> <p>LAST NAME</p> {{ form.last_name }} </div> <div class="email {% if form.email.errors %}form-error{% endif %}"> <p>EMAIL</p> {{ form.email }} </div> <div class="phone {% if form.phone.errors %}form-error{% endif %}"> <p>PHONE</p> {{ form.phone }} </div> <div class="resume-container {% if form.resume.errors %}form-error{% endif %}"> <p>ATTACH PDF RESUME</p> <input class="readonly" type="text" READONLY> <div class="resume"> {{ form.resume }} <div id="browse"> <a>BROWSE</a> </div> </div> </div> <div … -
NoReverseMatch when href name in urls
I get NoReverseMatch when using {% url 'detail' a.id %} in my template. I have not included $ in my urls. Found that on a google search. This is my main urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^item/', include('item.urls')), url(r'^status/', include('status.urls')), ] and my status.urls urlpatterns = [ # /status/ url(r'^$', views.index, name='index'), # /status/<status_id>/ url(r'^(?P<status_id>[0-9]+)/$', views.detail, name='detail'), ] It work if I remove {% url 'detail' a.id %}and hardcode status/{{ a.id }} I don't understand where I'm going wrong. -
Using Ajax in django template to update an element
So I have a button that is suppose to "Add" an "Item" to a list and update the list on the same page without refreshing it. Adding the Item without redirecting worked. but the element is not refreshed properly Here is my script: <script> $('#add').click(function () { $.get('/url/page/', function (data) { $('#element').html(data); }); }); </script> I feel like I have to add something in the views? and maybe use json code? -
Keep user django channels OAuth2 authenticatio
I am authenticating user on connect with this Mixin: import functools from channels.handler import AsgiRequest from rest_framework.exceptions import AuthenticationFailed from rest_framework.settings import api_settings authenticators = [auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES] def rest_auth(func): """ Wraps a HTTP or WebSocket connect consumer (or any consumer of messages that provides a "cookies" or "get" attribute) to provide a "http_session" attribute that behaves like request.session; that is, it's hung off of a per-user session key that is saved in a cookie or passed as the "session_key" GET parameter. It won't automatically create and set a session cookie for users who don't have one - that's what SessionMiddleware is for, this is a simpler read-only version for more low-level code. If a message does not have a session we can inflate, the "session" attribute will be None, rather than an empty session you can write to. Does not allow a new session to be set; that must be done via a view. This is only an accessor for any existing session. """ @functools.wraps(func) def inner(message, *args, **kwargs): # Make sure there's NOT a http_session already try: # We want to parse the WebSocket (or similar HTTP-lite) message # to get cookies and GET, but we … -
importing python module failed
I am trying to run the development server by using, django-admin runserver and python -m django runserver, the django-admin runserver works but the python -m django runserver gives the following error > Traceback (most recent call last): > File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/__main__.py", > line 9, in <module> > management.execute_from_command_line() > File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", > line 367, in execute_from_command_line > utility.execute() > File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", > line 359, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) > File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", > line 208, in fetch_command > klass = load_command_class(app_name, subcommand) > File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", > line 40, in load_command_class > module = import_module('%s.management.commands.%s' % (app_name, name)) > File "/home/mohit/anaconda3/lib/python3.6/importlib/__init__.py", line 126, > in import_module > return _bootstrap._gcd_import(name[level:], package, level) > File "<frozen importlib._bootstrap>", line 978, in _gcd_import > File "<frozen importlib._bootstrap>", line 961, in _find_and_load > File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked > File "<frozen importlib._bootstrap>", line 655, in _load_unlocked > File "<frozen importlib._bootstrap_external>", line 678, in exec_module > File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed > File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/commands/runserver.py", > line 12, in <module> > from django.core.servers.basehttp import get_internal_wsgi_application, run > File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", > line 15, in <module> > from wsgiref import simple_server > File "/home/mohit/anaconda3/lib/python3.6/wsgiref/simple_server.py", line > 13, in <module> > from http.server import BaseHTTPRequestHandler, HTTPServer > File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/http/__init__.py", … -
How do I populate fields from many-to-many tables using accessors in django-tables2?
I'm trying to create a table using django-tables2 that uses data from multiple tables, including a many-to-many relational table, using accessors. The problem is, while I can successfully populate the table with data directly from the model mentioned in the tables Meta class, I don't know how to successfully pull related data in other tables. I have three tables: Compounds, Names, and LinkCompoundsNames. Compound has a name field, which is simply one of its associated names that's chosen to be the definitive name to represent the compound. For example, compound_423121 might have the name "Aspirin", but it also has twelve other names associated with it by id in the LinkCompoundsNames table. In the end I'd like a visual table of Compounds with their name next to their id, and the ability to click a name and expand a field to see its other associated names. Here is my models.py: class Compound(models.Model): compound_id = models.AutoField(primary_key=True) compound_name = models.ForeignKey(Name, db_column='compound_name', null=True, on_delete=models.PROTECT) class Meta: db_table = 'compounds' class Name(models.Model): name = models.TextField(primary_key=True) name_type = models.ForeignKey(NameType, db_column='name_type', null=True, on_delete=models.PROTECT) def __str__(self): return self.name class Meta: db_table = 'names' # pairing compounds and names class LinkNameCompound(models.Model): link_name_compound_pk = models.AutoField(primary_key=True) compound_id = models.ForeignKey(Compound, db_column='compound_id', null=False, … -
Django / mysqlclient looking for missing `libmysqlclient.18.dylib` file
I've setup a Django (1.8.18) environment using virtualenv (Python 2.7.10) and also installed MariaDB (10.2.6) on my Mac via homebrew. Django is setup to use MySQL through the settings.py file and also I've installed mysqlclient. When I runserver I get a error saying: Error loading MySQLdb module: dlopen(/Users/wolfie/Code/django.thingy/.venv/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded: /usr/local/opt/mariadb/lib/libmysqlclient.18.dylib I've had a look in that /usr/local/opt/mariadb/lib/ folder and all I see close to that is libmariadb.3.dylib libmariadb.dylib -> libmariadb.3.dylib Is there any reason why Django/mysqlclient is looking for for the wrong file or is it MariaDB is missing a file it should have? -
Preserve Django user in channels and OAuth2
I'm creating an app in which I need to add a chat. The rest of my web app communicate over REST API with the server and for the authentication, I am using OAuth2 tokens. I found this mixin: https://gist.github.com/leonardoo/9574251b3c7eefccd84fc38905110ce4 import functools from channels.handler import AsgiRequest from rest_framework.exceptions import AuthenticationFailed from rest_framework.settings import api_settings authenticators = [auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES] def rest_auth(func): """ Wraps a HTTP or WebSocket connect consumer (or any consumer of messages that provides a "cookies" or "get" attribute) to provide a "http_session" attribute that behaves like request.session; that is, it's hung off of a per-user session key that is saved in a cookie or passed as the "session_key" GET parameter. It won't automatically create and set a session cookie for users who don't have one - that's what SessionMiddleware is for, this is a simpler read-only version for more low-level code. If a message does not have a session we can inflate, the "session" attribute will be None, rather than an empty session you can write to. Does not allow a new session to be set; that must be done via a view. This is only an accessor for any existing session. """ @functools.wraps(func) def inner(message, … -
Sort DRF serializer output of nested Serializer field by child's field
I have two serializers, in which one refers to the other with a many=True relationship. class AttributeInParentSerializer(ModelSerializer): masterdata_type = CharField(max_length=256, source='masterdata_type_id') class Meta: model = Attribute fields = ('uuid', 'masterdata_type') class ArticleInArticleSetSerializer(ModelSerializer): attributes = AttributeInParentSerializer(many=True) class Meta: model = Article fields = ('uuid', 'attributes') The ordering of the attributes in the Article are not always the same, but I want to output them in the same order, so in this case ordering on the field masterdata_type. How can I accomplish this? Note that I do not want to change any client of the serializer if possible, and surely not any model.