简体   繁体   English

如何使用 Django、Python(可能还有 Javascript)手动重新排序对象列表?

[英]How do I reorder a list of objects manually using Django, Python, (and possibly Javascript)?

Here is my code.这是我的代码。 models.py模型.py

from django.db import models


class Photo(models.Model):
    file = models.ImageField(upload_to='media/images')

class Album(models.Model):
    title = models.CharField(max_length=100)
    photos = models.ManyToManyField(Photo,related_name="photos",blank=True)

admin.py管理员.py

from django.contrib import admin
from .models import Photo, Album
# Register your models here.

class AlbumAdmin(admin.ModelAdmin):
    list_display = ("title","published")
    filter_horizontal = ("photos",)
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "photos":
            kwargs["queryset"] = Photo.objects.order_by("-id")
        return super(AlbumAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
        
admin.site.register(Photo)
admin.site.register(Album, AlbumAdmin)

views.py视图.py

from django.shortcuts import render
from django.conf import settings

from .models import Photo, Album

# Create your views here.

def album(request, album_title):
    album = Album.objects.get(title=album_title)
    context = {
        "album":album,
    }
    return render(request, "photos/album.html", context)

I am trying to achieve a page that shows the photos in each album and has a drag-and-drop function that allows a manual re-ordering of the photos in each album.我正在尝试实现一个页面,该页面显示每个相册中的照片,并有一个拖放 function 允许手动重新排序每个相册中的照片。 Then I wish to save the order of the album.然后我想保存专辑的顺序。 The only problem is, I have no clue to how to do this.唯一的问题是,我不知道如何做到这一点。

It's not a trivial task, so you can't just expect a one line answer, but I guess it's a good use case to have a look at some packages that try to solve this.这不是一项微不足道的任务,因此您不能只期望一条线的答案,但我想看看一些试图解决这个问题的包是一个很好的用例。

Here is a good overview of all packages that try to solve ordering, maybe one of them fits you well: https://djangopackages.org/grids/g/model-ordering/以下是尝试解决订购问题的所有软件包的一个很好的概述,也许其中一个非常适合您: https://djangopackages.org/grids/g/model-ordering/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM