在我的django应用程序中,我试图理解多对多关系,并且我使用formset来存储数据,如下所示:
Views.py
def Team_Form(request):
if request.POST:
form = TeamForm(request.POST)
form.player_instances = PlayerFormset(request.POST)
if form.is_valid():
team= Team()
team.tname= form.cleaned_data['tname']
team.save()
if form.player_instances.cleaned_data is not None:
for item in form.player_instances.cleaned_data:
player = Player()
player.pname= item['pname']
player.hscore= item['hscore']
player.age= item['age']
player.save()
team.player.add(player)
team.save()
else:
form = TeamForm()
return render(request, 'packsapp/employee/new.html', {'form':form})
Models.py
class Player(models.Model):
pname = models.CharField(max_length=50)
hscore = models.IntegerField()
age = models.IntegerField()
def __str__(self):
return self.pname
class Team(models.Model):
tname = models.CharField(max_length=100)
player= models.ManyToManyField(Player)
def __str__(self):
return self.tname
Forms.py
class PlayerForm(forms.Form):
pname = forms.CharField()
hscore= forms.IntegerField()
age = forms.IntegerField()
PlayerFormset= formset_factory(PlayerForm)
class TeamForm(forms.Form):
tname= forms.CharField()
player= PlayerFormset()
我无法理解的是,如何编辑我刚刚保存的表单集,或者更好地表达问题,即如何将保存的实例传递给表单集以对其进行编辑?
这里的多对多意味着一个球员可以在多个团队中,而且一个团队可以有很多球员。
要解决您的问题,您必须创建另一个视图(链接到相同的表单),该视图将显示您的表单但已经填写。在您的团队的功能pk中。
def updateTeam(request,pk):
team = Team.objects.get(id=pk)
form = TeamForm(instance=team)
if request.method == "POST":
form = TeamForm(request.POST, instance=team)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'accounts/order_form.html', context)
应该可以解决您的问题!
如有任何疑问,请不要犹豫