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

<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”对象没有属性“用户名”

最佳答案

您可以通过playerstatsform attribute [Django-doc](它是字典)从.cleaned_data获取值。通过使用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)

关于python - 'PlayerStatsForm'对象没有属性'username',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56119568/

10-12 22:05