我的参赛者模型与类别具有多对一的关系。我希望奖项的创建者只能访问他在实例化参赛者模型中创建的奖项的最后15个类别。也就是说,“竞争者”字段(类别)中的多选查询集将仅显示“类别模型”中最近创建的15个类别的列表。我做出了不同的努力,但是代码不起作用或给出了[['ManagementForm数据丢失或已被篡改']'错误。
我进行了无数次代码重构,并尝试采用在Internet上找到的解决方案。但是他们没有用。
# MY CATEGORY MODEL
class Category(models.Model):
award = models.ForeignKey(Award, on_delete=models.CASCADE)
award_category = models.CharField(max_length=150, blank=True, null=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.award_category
# MY CONTESTANT MODEL
class Contestant(models.Model):
award_name = models.ForeignKey(Award, on_delete=models.CASCADE)
contestant_name = models.CharField(max_length=150, null=True, blank=True )
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='contestants')
vote = models.IntegerField()
def number_of_vote(self):
return Contestant.objects.filter(self.vote).count()
vote_count = property(number_of_vote)
#MY VIEW
def get_award(request, pk):
new_award = get_object_or_404(Award, pk=pk)
Contest_Formset = modelformset_factory(Contestant, fields('contestant_name', 'category',), extra=15)
formset = Contest_Formset(request.POST)
for form in formset:
form.fields['category'].queryset = Category.objects.filter(user=request.user)[1:15]
if request.method == 'POST' and form.is_valid():
myform = form.save(commit=False)
myform.award_name = new_award
myform.save()
return redirect('award_details', pk=new_award.pk)
else:
formset = Contest_Formset()
context = {
'new_award': new_award,
'formset': formset
}
return render(request, 'voting/get_award.html', context)
# TEMPLATE
<form action=" " method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ formset.management_form }}
{{ formset }}
<input type="submit" value="save">
</form>
我希望参赛者的“类别”字段的输出仅显示登录用户创建的最后15个类别。