基于Django模型的表单将ForeignKey显示为复选框

时间:2019-06-14 13:00:52

标签: django forms

我想将Track模型名称(即Playlist模型中的ForeignKey()字段)显示为模板中复选框的列表。我知道什么是“ CheckboxSelectMultiple”,但是我不知道如何在我的情况下实现它。

这是我的“播放列表”模型:

class Playlist(models.Model):
    title = models.CharField(max_length=40, null=True)
    description = models.CharField(max_length=500, null=True)
    author = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    miniature = models.ImageField(upload_to='images/playlist', default="defaults/default.png", validators=[validate_miniature_file_extension])
    tracks = models.ManyToManyField(Track)
    favourite = models.BooleanField(default=False)

    def __str__(self):
        return self.title

这是我的“跟踪”模型:

class Track(models.Model):
    title = models.CharField(max_length=40, null=True)
    description = models.CharField(max_length=500, null=True)
    author = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    miniature = models.ImageField(upload_to='images/track', default="defaults/default.png", validators=[validate_miniature_file_extension])
    audio_or_video = models.FileField(upload_to='audio_and_video/', default="file_not_found", validators=[validate_track_file_extension])
    favourite = models.BooleanField(default=False)

    def __str__(self):
        return self.title

这是表格:

class AddPlaylist(forms.ModelForm):
    class Meta:
        model = models.Playlist
        fields = ['title', 'description', 'tracks', 'miniature', 'favourite']
        widgets = {
            'description': Textarea(attrs={'cols': 30, 'rows': 10}),
        }

0 个答案:

没有答案