'PlayerStatsForm'对象没有属性'username'

时间:2019-05-13 20:35:46

标签: python html django

我正在创建一个搜索栏,该栏需要一个用户名并在数据库中找到该Player。我创建一个接受请求的PlayerStatsForm(),使用请求中的用户名在数据库中搜索玩家,然后返回该玩家的统计信息。我知道用户名通过html表单正确传递给了我的python代码,并且表单对PlayerStatsForm.is_valid()传递了true,但是当我尝试调用playerstatsform.username时,它说未找到该属性。如果我添加model = Player并在PlayerStatsForm中将form.Form更改为ModelForm,它将尝试将没有用户名或ID的玩家插入数据库,并说user_id列不能为空

<tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" value="testuser" required id="id_username"></td></tr>
Internal Server Error: /elousers/elosearch/

这是来自终端的错误,是id = id_username而不是name = id_username的问题吗?

playerstatsform:


class PlayerStatsForm(forms.Form):
    username = forms.CharField()

    class Meta:
        fields = (
            'username',
        )

views.py:

def elosearch(request):
    if request.method == 'POST':
        print("Post was found")
        if 'get_player' in request.POST:
            playerstatsform = PlayerStatsForm(request.POST)
            print("post found")
            if playerstatsform.is_valid():
                player = Player.objects.get(name=playerstatsform.cleaned_data['username'])
                print("player found successfully")
                player_elo = player.elo
                player_name = player.name
                print(player_elo)
                context1 = {'playername': player_name, 'playerelo': player_elo}
                return render('elousers/elosearch.html', context1)
            else:
                invalid_player_entry = "Username not added. Please register below."
                context1 = {'invalid_player': invalid_player_entry}
                return render(request, 'elousers/elosearch.html', context1)
        elif 'addgame' in request.POST:
            gameform = GameForm(data=request.POST)
            if gameform.is_valid():
                gameform.save()
                game_success = "Game Successfully Added!"
                context2 = {'game_display': game_success}
                return render(request, 'elousers/elosearch.html', context2)
            else:
                game_invalid = "Invalid entry. Please try again."
                context2 = {'game_display': game_invalid}
                return render(request, 'elousers/elosearch.html', context2)
        else:
            return render(request, 'elousers/elosearch.html')
    elif request.method == 'GET':
        print("get was called")
        return render(request, 'elousers/elosearch.html')

期待数据库使用表单提供的用户名进行查询,但是我得到的“ PlayerStatsForm”对象没有属性“ username”

1 个答案:

答案 0 :(得分:0)

您可以从playerstatsform.cleaned_data attribute [Django-doc](是字典)中获取值。通过使用playerstatsform.username,您可以访问form字段,但是如果通过str传递该字段,则将呈现该字段的HTML表示形式。

def elosearch(request):
    if request.method == 'POST':
        print("Post was found")
        if 'get_player' in request.POST:
            playerstatsform = PlayerStatsForm(request.POST)
            if playerstatsform.is_valid():
                player = Player.objects.get(name=playerstatsform.cleaned_data['username'])
                player_elo = player.elo
                player_name = player.name
                context1 = {'playername': player_name, 'playerelo': player_elo}
                return render(request, 'elousers/elosearch.html', context1)

请注意,给定的Player可能没有name对象,或者,如果该字段不是unique=True,则多个Player可以拥有名称,因此您可能应该至少try-catch这些情况,并进行相应处理。

因此,您可能需要执行以下操作:

def elosearch(request):
    if request.method == 'POST':
        print("Post was found")
        if 'get_player' in request.POST:
            playerstatsform = PlayerStatsForm(request.POST)
            if playerstatsform.is_valid():
                try:
                    player = Player.objects.get(
                        name=playerstatsform.cleaned_data['username']
                    )
                except (Player.DoesNotExist, Player.MultipleObjectsReturned):
                    player = None
                    player_elo = None
                    player_name = None
                else:
                    player_elo = player.elo
                    player_name = player.name
                context1 = {'playername': player_name, 'playerelo': player_elo}
                return render(request, 'elousers/elosearch.html', context1)