Django表格检查

时间:2015-08-23 14:13:35

标签: python django forms django-forms django-validation

我有以下表格:

    <form action="" method="post">
        {% csrf_token %}
        <select name="selectTeamOne">

            {% for x in currentTeams %}

                {% if x.teamid != 66 %}

                    <option value={{x.teamid}}>{{x.teamname}}</option>

                {% endif %}

            {% endfor %}

        </select>

        <select name="selectTeamTwo">

            {% for x in currentTeams %}

                <option value={{x.teamid}}>{{x.teamname}}</option>

            {% endfor %}

        </select>

        <input type="submit" value="Submit" />
    </form>

这是由以下观点驱动的:

def selectteams(request, soccerseason, fixturematchday):

    if request.method == 'POST':

        if form.is_valid():

            return HttpResponse("Two different teams were selected.")

        else:
            return HttpResponse("Two different teams were not selected.")


    fixtures = StraightredFixture.objects.filter(soccerseason=soccerseason,fixturematchday=fixturematchday).order_by('fixturedate')

    currentTeams = StraightredTeam.objects.filter(currentteam=1).order_by('teamname')

    cantSelectTeams = UserSelection.objects.filter(campaignno=389100069).order_by('campaignno')

    return render(request, 'straightred/test.html',
                  {'fixtures' : fixtures,
                   'currentTeams' : currentTeams,
                   'cantSelectTeams' : cantSelectTeams,
                   'soccerseason' : soccerseason,
                   'fixturematchday' : fixturematchday})

我只是想知道检查用户是否从下拉列表中选择了同一个团队两次的最佳方法,并返回相关的HttpResponse,如上所示。

任何建议指出我正确的方向表示赞赏。非常感谢,艾伦。

1 个答案:

答案 0 :(得分:1)

您可以在django表单上强制执行服务器级验证: https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

来自django 1.8的文档:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"myentity" inManagedObjectContext:managedObjectContext];
NSDictionary *propertiesByName = [entity propertiesByName];
fetchRequest.propertiesToFetch = @[[propertiesByName objectForKey:@"my_field_2"],[propertiesByName objectForKey:@"my_field_3", [propertiesByName objectForKey:@"my_field_4"]];