保存我的Django表单前如何访问某些数据?

时间:2019-05-02 09:50:43

标签: django validation

我目前正在建立一个锦标赛经理,由于对Django的经验不足,所以我无法参加程序。 所以,基本上,我有一个视图来管理锦标赛的添加团队系统。我有一个“锦标赛”模型,其中包含一个字段,该字段指示我可以在一个类别中拥有的团队数(“类别”是另一个字段)。在类别和锦标赛之间存在多对一关系。我也有一个“团队”模型,团队和类别之间存在多对一关系。所以我的问题是,如何根据“比赛”中的字段检查是否可以添加类别中的团队?我指定在两个不同的锦标赛中可以有相同的类别。

views.py

def team_view(request, id, *args, **kwargs):
    tournaments = Tournament.objects.filter(user=request.user)
    tournament = Tournament.objects.get(pk=id)

    form_team = TeamCreationForm(request.POST or None)
    form_team.fields['category'].queryset = Category.objects.filter(tournament=tournament)

    if form_team.is_valid():

        form_team.save()
        form_team = TeamCreationForm()
        form_team.fields['category'].queryset = Category.objects.filter(tournament=tournament)

    context = {
        'tournaments': tournaments,
        'tournament': tournament,
        'form_team': form_team,
    }
    return render(request, "tournament_manage_team.html", context)

forms.py

class MyModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.description

class TeamCreationForm(forms.ModelForm):

    name                = forms.CharField(label='Name', widget=forms.TextInput(attrs={
                                    'class':'form-control',
                                    'placeholder': 'Enter the name of the team'}))
    category            = MyModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(attrs={
                                    'class':'form-control'}))

    class Meta:
        model = Team
        fields = [
            'name',
            'category',
        ]

models.py

class Tournament(models.Model):
    name                = models.CharField(max_length=32)
    dateStart           = models.DateField(auto_now=False, auto_now_add=False)
    dateEnd             = models.DateField(auto_now=False, auto_now_add=False)
    nbMaxTeam           = models.IntegerField()
    # nameGymnasium     = models.CharField(max_length=32, blank=True, null=True)
    # addressGymnasium  = models.CharField(max_length=254, blank=True, null=True)
    sport               = models.ForeignKey(Sport, default=None, on_delete=models.CASCADE)
    user                = models.ForeignKey(CustomUser, default=None, on_delete=models.CASCADE)

class Category(models.Model):
    description = models.CharField(max_length=128)
    tournament  = models.ForeignKey(Tournament, default=None, on_delete=models.CASCADE) 

class Team(models.Model):
    name        = models.CharField(max_length=16)
    totalpoints = models.IntegerField(default=0)
    position    = models.IntegerField(default=0)
    matches     = models.ManyToManyField(Match, default=None, blank=True)
    category    = models.ForeignKey(Category, default=None, on_delete=models.CASCADE)

我想我必须在 is_valid() 方法中进行检查,但是如何获得在表单中选择的类别以及与我要添加比赛的锦标赛相关的类别团队?

0 个答案:

没有答案