我试图修改我的数据库的现有行,它来自名为" CharacterSkill"的中间表。具有独特的共同约束:
models.py
class CharacterSkill(models.Model):
character = models.ForeignKey(Character, on_delete=models.CASCADE)
level = models.IntegerField(default=0)
skill = models.ForeignKey(Skill, on_delete=models.CASCADE)
class Meta:
unique_together = ("character","skill")
我做了一个表单来更改级别,但我无法保存表单,我有来自两个字段的两条错误消息"字符" &安培; "技能":
Select a valid choice. That choice is not one of the available choices.
请帮忙吗? :)
我的表格:
class SkillCreateForm(forms.ModelForm):
class Meta:
model = CharacterSkill
fields = ('skill','level','character',)
我的观点:
def skill_update(request,skillpk,instancepk):
form = SkillCreateForm(request.POST)
user = User.objects.get (id = request.user.id)
instance = Character.objects.get (id = instancepk)
skill = CharacterSkill.objects.get(id = skillpk)
data = {'character' : instance,
'skill' : skill.skill,
'level' : skill.level,
}
if form.is_valid():
form.save()
return redirect('persomaker:skill_list', instance.id)
else:
form = SkillCreateForm(data)
#form.fields['skill'].widget = HiddenInput()
#form.fields['character'].widget = HiddenInput()
return render(request, 'character/create_skill.html',
{'instance':instance,
'skill':skill,
'form': form,})
答案 0 :(得分:0)
基于一本书,我改变了我将表格限制为使用实例的方式:
def skill_update(request,skillpk,instancepk):
user = User.objects.get (id = request.user.id)
instance = Character.objects.get (id = instancepk)
skill = CharacterSkill.objects.get(id = skillpk)
if request.method == "POST":
form = SkillModifyForm(request.POST,instance = skill,)
print (skill)
if form.is_valid():
form.save()
return redirect('persomaker:skill_list', instance.id)
else:
form = SkillModifyForm(instance = skill,)
return render(request, 'character/create_skill.html',
{'instance':instance,
'skill':skill,
'form': form,})