Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure reordering order_with_respect_to items in the Django admin?

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.

like image 331
Natim Avatar asked Nov 06 '22 10:11

Natim


1 Answers

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__'
like image 55
Sean Arc Avatar answered Nov 14 '22 21:11

Sean Arc