编辑时如何在管理面板中选中CheckboxSelectMultiple?

时间:2019-08-01 11:40:47

标签: django django-models django-forms

我是一名新的Django程序员,当前使用的Django版本是1.11.20。

我创建了模型:餐厅和设施。

facilities = (
        (1,'Accepts Credit Cards'),
        (2,'Wireless Internet'),
        (3,'Privat Parking'),
        (4,'Wheelchair Accesible'),
        (5,'Bike Parking'),
        (6,'Reservations'),
        (7,'Smoking Area'),
        (8,'Coupons'),
    )
class Restaurant(models.Model):
restaurant_name     = models.CharField(max_length=255)
location            = models.ForeignKey(Places, on_delete=models.CASCADE)
restaurant_overview = RichTextField(blank=True)
users_rating        = models.DecimalField(decimal_places=1, max_digits=2)
restaurant_image    = models.ImageField(upload_to='restaurants')
created_at          = models.DateTimeField(auto_now=True)
updated_at          = models.DateTimeField(auto_now_add=True)


class Menu(models.Model):
    restaurant  = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    menu_name   = models.CharField(max_length=255)
    menu_items  = RichTextField(blank=True)



class Facilities(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    items      = models.CharField(max_length=255)

创建了一个表单,用于在管理面板中将设施的字符字段转换为可多选的复选框。我的forms.py中的代码如下:

from .models import Facilities, facilities

class FacilitiesForm(forms.ModelForm):
    items = forms.MultipleChoiceField(choices=facilities, widget=forms.CheckboxSelectMultiple)

    class Meta:
        model   = Facilities
        exclude = ['created_at', 'updated']

我的管理面板中的代码:

class MenuInline(admin.TabularInline):
    model   = Menu
    max_num = 1

class FacilitiesInline(admin.TabularInline):
    model  = Facilities
    form   = FacilitiesForm 
    max_num= 1


class RestaurantAdmin(admin.ModelAdmin):
    inlines = [
        # RestaurantInline,
        MenuInline,
        FacilitiesInline,
    ]

admin.site.register(Restaurant, RestaurantAdmin)    

在创建新记录时工作正常。但是,当我编辑现有记录时,复选框设置为未选中。编辑记录时如何保持复选框的状态?我是否需要重写ModelForms保存方法或在admin.py中进行一些更改?

0 个答案:

没有答案