我是Django的新手。我想用另一个模型中的动态标签/详细名称填充模型Score的表单:问题。
基本上,每个用户有5个当前的问题,他们将以“是”或“否”的形式对其进行评分
我将用户当前五个问题的数据保存在字典中,并且可以将此字典传递到视图或模板中,但不知道如何使用字典来填充表单的标签/详细名称。
#Model
class Score(models.Model):
yesno = ((0,"No"),(1,"Yes"),)
oneScore =models.IntegerField(choices=yesno,default='none')
twoScore =models.IntegerField(choices=yesno,default='none')
threeScore =models.IntegerField(choices=yesno,default='none')
fourScore =models.IntegerField(choices=yesno,default='none')
fiveScore =models.IntegerField(choices=yesno,default='none')
author = models.ForeignKey('auth.User')
date_created = models.DateTimeField(blank=False, null=False)
#Model
class QuestionManager(models.Manager):
def current_for_user(self,user):
question1 = Question.objects.filter(author=user,statementNumber=1).order_by('-id').first()
question2 = Question.objects.filter(author=user,statementNumber=2).order_by('-id').first()
question3 = Question.objects.filter(author=user,statementNumber=3).order_by('-id').first()
question4 = Question.objects.filter(author=user,statementNumber=4).order_by('-id').first()
question5 = Question.objects.filter(author=user,statementNumber=5).order_by('-id').first()
question_list = {"1":question1,
"2":question2,
"3":question3,
"4":question4,
"5":question5}
return question_list
class Question(models.Model):
statementNumber=models.IntegerField(choices=NUMBER, default='1',verbose_name="The number of the statement")
text = models.CharField(max_length=500,help_text="Enter your text", verbose_name="New Statement")
author = models.ForeignKey('auth.User')
date_created = models.DateTimeField(blank=False, null=False)
objects=QuestionManager()
#Form
class ScoreForm(forms.ModelForm):
class Meta:
model = Score
fields = ('oneScore','twoScore','threeScore','fourScore','fiveScore','bigScore')
#View
def score(request):
user = request.user
questions = Question.objects.current_for_user(user)
if request.method == "POST":
questions = Question.objects.current_for_user(user)
form = ScoreForm(request.POST)
if form.is_valid():
score = form.save(commit=False)
score.author = request.user
score.save()
return redirect('scoresheet',pk=score.pk)
else:
form = ScoreForm()
return render(request,'MC/score.html',{'form': form,'questions':sorted(questions.items())})
答案 0 :(得分:0)
我不确定你追求的是什么,但你可以将任何你喜欢的东西传递给表格:
class ScoreForm(forms.ModelForm):
def __init__(self, questions, *args, **kwargs):
super().__init__(*args, **kwargs)
for num, question in questions.items():
self.fields.get('some_field').label = question
#View
def score(request):
user = request.user
questions = Question.objects.current_for_user(user)
if:
# ...
else:
form = ScoreForm(questions)
return render(request,'MC/score.html',{'form': form})