5

I am trying to use the order_with_respect_to Django Meta option and reorder items in the admin.

I found https://github.com/bfirsh/django-ordered-model but they doesn't seem to use the native Django API for it.

Do you know does one add this reorder functionality to the Django admin?

The model looks like this:

from django.db import models

class Question(models.Model):
    text = models.TextField()

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    text = models.TextField()

    class Meta:
        order_with_respect_to = 'question'

I'd like to be able to reorder the answer from the admin.

Natim
  • 17,274
  • 23
  • 92
  • 150
  • What does your model/admin class look like & how it is behaving differently to what you want? – markwalker_ Jan 13 '20 at 15:05
  • I added an example. – Natim Jan 13 '20 at 15:13
  • I had this exact problem too. Django assumes you never want to reorder "Answers", just leave them in the same order as they were when created. My workaround was to add my own field on the model, named "order", make it an integer field, then on its `admin.TabularInline` class override `get_queryset()` to order by "order". – thespacecamel Mar 21 '20 at 21:31

1 Answers1

1

I don't know if this is the best way, but it appears to work: You can provide your own ModelForm to the admin, including an extra field (like here: django-admin-add-custom-form-fields-that-are-not-part-of-the-model).

The code for the above example could look something like this (forms.py):

from django import forms

from .models import Question

class QuestionAdminForm(forms.ModelForm):
    assign_order = forms.CharField(
        max_length=50,
        help_text=("Enter order of ids in comma separated list, "
                   "e.g. '0,1,2,3'")
        )

    def save(self, commit=True):
        instance = super().save(commit)
        assign_order = self.cleaned_data.get('assign_order', None)
        order_list = [int(num) for num in assign_order.split(',')]
        instance.set_answer_order(order_list)
        if commit:
            instance.save()
        return instance

    class Meta:
        model = Question
        fields = '__all__'
Sean Arc
  • 21
  • 1