0
我有一個Django表單集,我真的不能解釋自己的問題。 這是涉及的代碼。Django的表單集帖額外的(和空白)行
forms.py:
class ScoreForm(forms.ModelForm):
class Meta:
model = models.Score
fields = (
'period',
'home_team_score',
'away_team_score',
)
ScoreFormSet = forms.inlineformset_factory(
models.Fixture,
models.Score,
form=ScoreForm,
extra=5
)
models.py:
class Score(models.Model):
fixture = models.ForeignKey(Fixture, related_name="score")
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="score")
inserted_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
period = models.IntegerField(blank=True, null=True)
home_team_score = models.IntegerField(blank=True, null=True)
away_team_score = models.IntegerField(blank=True, null=True)
class Meta:
db_table = 'score'
views.py:
class InsertScoreView(CreateView):
form_class = forms.ScoreForm
model = Score
template_name = 'gamestream/insert_score.html'
success_url = "/gamestream/score_list/"
def get_context_data(self, **kwargs):
fixture = Fixture.objects.get(id=self.kwargs['fixture_id'])
data = super(InsertScoreView, self).get_context_data(**kwargs)
if self.request.POST:
data['scores'] = forms.ScoreFormSet(self.request.POST)
data['fixture'] = fixture
else:
data['scores'] = forms.ScoreFormSet()
data['fixture'] = fixture
return data
def form_valid(self, form, **kwargs):
user = self.request.user
fixture = Fixture.objects.get(id=self.kwargs['fixture_id'])
context = self.get_context_data()
formset = forms.ScoreFormSet(self.request.POST)
if formset.is_valid():
scores = formset.save(commit=False)
for score in scores:
score.fixture = fixture
score.user = user
score.save()
return super(InsertScoreView, self).form_valid(form)
和模板:
<div class="container">
<h3>Please insert scores for the following match:</h3>
<h4>{{ fixture.starting_time }} -- {{ fixture.league.league_name }} -- {{ fixture.home_team }} vs {{ fixture.away_team }}</h4>
<form action="." method="POST">
{% csrf_token %}
{{ scores.management_form }}
{% for form in scores %}
<p>{{ form }}</p>
{% endfor %}
<input type="submit" value="Insert score" class="submit" />
</form>
</div>
我得到這個行爲: 我能夠插入所有我想要的值。無論它們是1還是5,它們都插入並保存到db中(這是正確的,這就是我想要實現的)。 的問題是,它看起來像和額外的100%的空白表單獲得通過發送和不驗證(因爲需要夾具場)! 我已刪除的評分模型(用於測試目的)的燈具領域的約束和事實上完全空白的線插入到了分貝。 這就是爲什麼我相信正在發送一個空白表格通過。
我真的不能解釋這種行爲。這個空白表單(或其它什麼)來自哪裏?
感謝, 維托裏奧