如何根据模型id
填写表单中的字段?
我必须建模Match
和MatchRegister
。
登录的用户可以注册Match
,数据被写入MatchRegister
。
我现在正在创建用于编辑Match
对象的表单,并希望填充referee_a
表中的字段referee_b
和MatchRegister
的值(当然是为了进行编辑匹配)。
我不知道该怎么做。你能帮我吗?
class MatchForm(forms.Form):
class Meta:
model = Match
fields = (
'match_number', 'home_team', 'away_team', 'match_category',
'date_time', 'notes', 'referee_a', 'referee_b')
widgets = {
'match_number': forms.TextInput(attrs={'class': 'form-control'}),
'home_team': forms.Select(attrs={'class': 'form-control'}),
'away_team': forms.Select(attrs={'class': 'form-control'}),
'match_category': forms.Select(attrs={'class': 'form-control'}),
'date_time': forms.DateTimeField(attrs={'class': 'form-control'}),
'referee_a': forms.Select(attrs={'class': 'form-control'})
'referee_b': forms.Select(attrs={'class': 'form-control'})
'notes': forms.Textarea(attrs={'class': 'form-control'})
}
class MatchRegister(models.Model):
match = models.ForeignKey(
Match,
on_delete=models.SET_NULL,
null=True
)
ref_reg = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True
)
class Match(models.Model):
match_number = models.CharField(
max_length=10,
)
home_team = models.ForeignKey(
Team,
on_delete=models.SET_NULL,
null=True,
related_name='home_team',
)
away_team = models.ForeignKey(
Team,
on_delete=models.SET_NULL,
null=True,
related_name='away_team',
)
match_category = models.ForeignKey(
MatchCategory,
on_delete=models.SET_NULL,
null=True,
)
date_time = models.DateTimeField(
default=timezone.now,
)
notes = models.TextField(
max_length=1000,
blank=True,
)
last_update = models.DateTimeField(
auto_now=timezone.now
)
referee_a = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='referee_a',
)
referee_b = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='referee_b',
)