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.
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__'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With