[英]Form (or Formset?) to handle multiple table rows in Django
I'm working on my first Django application. 我正在研究我的第一个Django应用程序。 In short, what it needs to do is to display a list of film titles, and allow users to give a rating (out of 10) to each film. 简而言之,它需要做的是显示电影片名列表,并允许用户给每部电影评分(满分10分)。 I've been able to use the {{ form }} and {{ formset }} syntax in a template to produce a form which lets you rate one film at a time, which corresponds to one row in a MySQL table, but how do I produce a form that iterates over all the movie titles in the database and produces a form that lets you rate lots of them at once? 我已经能够在模板中使用{{form}}和{{formset}}语法来生成一个表单,该表单允许您一次评价一部电影,这对应于MySQL表格中的一行,但是如何做我制作了一个表格,它迭代数据库中的所有电影标题,并生成一个表格,让你一次评价它们的大部分?
At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean. 起初,我认为这是formsets的用途,但我看不出有什么方法可以自动迭代数据库表的内容来生成表单中的项目,如果你看到我的意思。
Currently, my views.py has this code: 目前,我的views.py有以下代码:
def survey(request):
ScoreFormSet = formset_factory(ScoreForm)
if request.method == 'POST':
formset = ScoreFormSet(request.POST, request.FILES)
if formset.is_valid():
return HttpResponseRedirect('/')
else:
formset = ScoreFormSet()
return render_to_response('cf/survey.html', {
'formset':formset,
})
And my survey.html has this: 我的survey.html有这个:
<form action="/survey/" method="POST">
<table>
{{ formset }}
</table>
<input type = "submit" value = "Submit">
</form>
Oh, and the definition of ScoreForm and Score from models.py are: 哦,ScoreForm和models.py的Score的定义是:
class Score(models.Model):
movie = models.ForeignKey(Movie)
score = models.IntegerField()
user = models.ForeignKey(User)
class ScoreForm(ModelForm):
class Meta:
model = Score
So, in case the above is not clear, what I'm aiming to produce is a form which has one row per movie, and each row shows a title, and has a box to allow the user to enter their score. 因此,如果上述情况不明确,我打算制作的是每部电影一行的形式,每行显示一个标题,并有一个框允许用户输入他们的分数。
If anyone can point me at the right sort of approach to this, I'd be most grateful. 如果有人能指出我正确的方法,我将非常感激。
"At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean." “起初,我认为这就是formset的用途,但我看不出有什么方法可以自动迭代数据库表的内容来生成表单中的项目,如果你看到我的意思。”
You need to get a queryset. 您需要获取一个查询集。 And you need to provide that queryset to your form as initial data. 并且您需要将该查询集作为初始数据提供给表单。 See using initial data with a formset for the code. 请参阅使用带有代码的formset的初始数据 。
initial = [ list of { dictionaries }, one per form ]
Interestingly, this is a direct feature of the model API through the values
method of a queryset. 有趣的是,这是模型API的直接功能,通过查询集的values
方法。
我找到了答案,使用modelformset_factory而不是formset_factory解决问题,谢谢......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.