我正在尝试为音乐家模型创建一个ModelForm,从中可以选择它 每个音乐家都有很多专辑。我认为这张专辑是反向的 ModelForm不会将相册值保存到数据库中。是否有任何可能的方法可以使这个工作
请帮助我,并提前致谢
这是我的模型形式:
class musicianForm(forms.ModelForm):
album=forms.ModelMultipleChoiceField(queryset=Musician.objects.all(),
widget=forms.widgets.CheckboxSelectMultiple())
class Meta:
model = Musician
fields = ('album','first_name','last_name','instrument')
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
class musicianAdmin(admin.ModelAdmin):
form = musicianForm
答案 0 :(得分:0)
执行此操作的最佳方法是覆盖表单的__init__
,如下所示:
class MusicianForm(forms.ModelForm):
musician = forms.CharField()
def __init__(self, *args, **kwargs):
super(MusicianForm, self).__init__(*args, **kwargs)
self.fields['musician'] = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple, choices=(((choice.id), choice) for choice in Musician.objects.all()))
class Meta:
model = Album
fields = ('name','release_date','num_stars')
然后在models.py
中,你必须创建另一个模型来将艺术家连接到相册。如果你不这样做,你只能在一个专辑中添加一个艺术家(可能有合作,所以我们必须这样做):
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
def __str__(self):
return self.first_name + " " + self.last_name
class Album(models.Model):
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
def __str__(self):
return self.name
class AlMu(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
album = models.ForeignKey(Album, on_delete=models.CASCADE)
然后处理我们的数据并连接所有内容,请执行以下操作:
def create_album(request):
if request.method == "POST":
form = MusicianForm(request.POST)
if form.is_valid():
mu = form.save(commit=False)
mu.name = form.cleaned_data['name']
mu.release_date = form.cleaned_data['release_date']
mu.num_stars = form.cleaned_data['num_stars']
mu.save()
for i in form.cleaned_data['musician']:
mus = Musician.objects.get(id=i)
AlMu(artist=mus, album=mu).save()
# do something fancy here. Redirect or so
else:
form = MusicianForm()
return render(request, 'create_album.html', {'form': form})
您的create_album.html
文件看起来像这样(没什么特别的):
<form method="POST">
{{form}}
<input type="Submit" value="Submit">
</form>