0

есть два HTML шаблона - swiss.html и swiss_result.html, на каждом форма с данными с методом post (method=“post”), формы одинаковые, НО из первой формы, POST передает во вьюху данные ФИО (что соответствует полю bill_fio в модели (атрибут класса)), т.е. ‘Петров’ ИЗ второго же шаблона, при повторном к нему обращении, POST передает во вьюху данные ФИО с префиксом имени модели? т.е. (имя можели Bill, - class Bill(models.Model): ) модель одна и таже, шаблоны идентичны, но почему так происходит ?

необходимо, что бы передавала во вьюшку только ФИО, без префикса

по коду:
из ф-ии def swiss() во вьюхе

def swiss(request):
args = {}
args.update(csrf(request))
index = Bill.objects.all()
nov_por = Bill.objects.filter().order_by('-bill_mat_ozh')

a = nov_por.count() // 2
nov_por_1 = (nov_por[:a])
nov_por_2 = (nov_por[a:])

res_1 = [(nov_por_1[n].bill_fio) for n in range(nov_por_1.count()) if nov_por_1[n] in nov_por_1]
res_2 = [(nov_por_2[n].bill_fio) for n in range(nov_por_2.count()) if nov_por_2[n] in nov_por_2]
players = zip_longest(res_1, res_2)

return render_to_response('swiss.html', {'players':players, 'index':index},
                          context_instance=RequestContext(request))

данные передаются в шаблон swiss.html:

<form action="{% url 'first_step' %}" method="post">
{% csrf_token %}
    <table border="1">
        {% for opponents_player in players %}
            {% if None not in opponents_player %}
                <tr>
                    <td>
                        {% for single_player_if_yes in opponents_player %}
                             {{ single_player_if_yes }} <br>
                        {% endfor %}
                    </td>
                    <td>
                        {% for single_player in opponents_player %}
                            <input type="radio" name="{{ opponents_player }}" value="{{ single_player }}">{{ single_player }} <br>
                        {% endfor %}
                            <input type="radio" name="{{ opponents_player }}" value="no">Ничья<br>
                    </td>
                </tr>
            {% else %}
                <tr>
                    <td>
                        {% for single_player_if_none in opponents_player %}
                            {% if single_player_if_none != None %}
                             {{ single_player_if_none }}
                            {% endif %}
                        {% endfor %}
                    </td>
                    <td>
                        {% for single_player in opponents_player %}
                            {% if single_player != None %}
                            <input type="radio" name="{{ opponents_player }}" value="{{ single_player }}" checked>{{ single_player }} <br>
                            {% endif %}
                        {% endfor %}
                    </td>
                </tr>
            {% endif %}
        {% endfor %}
    </table>
        <br>
        <input type="submit" value="Play">
</form>

далее по нажатии на кнопку Play данные с шаблона уходят в функцию first_step()

def first_step(request):
game_data = request.POST
print(game_data)
for key, value in game_data.items():

    if key == 'csrfmiddlewaretoken':
        pass

    elif value == 'no':
        split_player = key.split(', ')

        for player in split_player:
            player_name = re.sub(r'[^\w\s-]+', r'', player).strip()

            standoff = Bill.objects.get(bill_fio = player_name)
            standoff.swiss_bill_score = standoff.swiss_bill_score + 0.5
            standoff.save()

    else:
        bill = Bill.objects.get(bill_fio = value)
        bill.swiss_bill_score = bill.swiss_bill_score + 1
        bill.save()

for key, value in game_data.items():
    if key == 'csrfmiddlewaretoken':
        pass
    else:
        spisok = []
        if 'None' in key:
            pass
        else:
            wr_split_player = key.split(', ')
            for rw_player in wr_split_player:
                rw_player_name = re.sub(r'[^\w\s-]+', r'', rw_player).strip()

                rw_player_id = Bill.objects.get(bill_fio = rw_player_name).id
                spisok.append(rw_player_id)
                spisok.sort()


            length = len(spisok)
            if length == 2:
                rival_1 = Bill.objects.get(id = spisok[0])
                rival_2 = Bill.objects.get(id = spisok[1])
                rival_1.swiss_rivel = spisok[1]
                rival_2.swiss_rivel = spisok[0]
                rival_1.save()
                rival_2.save()
            else:
                pass



swiss_players = Bill.objects.all().order_by('-swiss_bill_score')
new_game = swiss_players.count() // 2
new_group_1 = (swiss_players[:new_game])
new_group_2 = (swiss_players[new_game:])

id_new_group_1 = []
id_new_group_2 = []

for n1 in new_group_1:
    igrok = Bill.objects.get(bill_fio = n1)
    id_igrok = igrok.id
    id_new_group_1.append(id_igrok)

for n2 in new_group_2:
    igrok = Bill.objects.get(bill_fio = n2)
    id_igrok = igrok.id
    id_new_group_2.append(id_igrok)


result_finish = []

for single_id in id_new_group_1:
    result = [single_id, random.choice(id_new_group_2)]
    print(request)

    if Bill.objects.get(id=result[0]).swiss_rivel is not None:
        while str(result[1]) in Bill.objects.get(id=result[0]).swiss_rivel:
            result = [single_id, random.choice(id_new_group_2)]
            break
    else:
        result = [single_id, random.choice(id_new_group_2)]

    id_new_group_2.remove(result[1])
    result_2 = [Bill.objects.get(id=result[0]), Bill.objects.get(id=result[1])]

    result_finish.append(result_2)

if id_new_group_2 != None:
    end_player = [None, Bill.objects.get(id=id_new_group_2[0])]
    result_finish.append(end_player)



return render_to_response('swiss_result.html', {'swiss_players':swiss_players, 'result_finish':result_finish},
                          context_instance=RequestContext(request))

которая в свою очередь передает значения и открывает шаблон swiss_result.html

<form action="{% url 'first_step' %}" method="post">
{% csrf_token %}
    <table border="1">
        {% for opponents_player in result_finish %}
            {% if None not in opponents_player %}
                <tr>
                    <td>
                        {% for single_player_if_yes in opponents_player %}
                             {{ single_player_if_yes }} <br>
                        {% endfor %}
                    </td>
                    <td>
                        {% for single_player in opponents_player %}
                            <input type="radio" name="{{ opponents_player }}" value="{{ single_player }}">{{ single_player }} <br>
                        {% endfor %}
                            <input type="radio" name="{{ opponents_player }}" value="no">Ничья<br>
                    </td>
                </tr>
            {% else %}
                <tr>
                    <td>
                        {% for single_player_if_none in opponents_player %}
                            {% if single_player_if_none != None %}
                             {{ single_player_if_none }}
                            {% endif %}
                        {% endfor %}
                    </td>
                    <td>
                        {% for single_player in opponents_player %}
                            {% if single_player != None %}
                            <input type="radio" name="{{ opponents_player }}" value="{{ single_player }}" checked>{{ single_player }} <br>
                            {% endif %}
                        {% endfor %}
                    </td>
                </tr>
            {% endif %}
        {% endfor %}
    </table>
        <br>
        <input type="submit" value="Play">
</form>

и вот повторное нажатие на Play, снова отдает данные ф-ии first_step во вьюхе и туда уже идут имена с префиксом имени модели почему так ? как от этого избавиться ? что бы не зависимо от количества обращений к этой форме, она отдавала только ФИО, без префиксов

1
  • приведи пример шаблонов и вьюх.
    – MichaelPak
    26 июл 2016 в 13:52

1 ответ 1

1

решено:
1. изначально не совсем корректно оправлял в шаблон <class 'itertools.zip_longest'>, преобразовал его в <class 'list'>
2. во вьюхе, в ф-ии def first_step нашел, что дописывало префикс в виде названия модели, это оказались строки

result_2 = [Bill.objects.get(id=result[0]), Bill.objects.get(id=result[1])]  
...
end_player = [None, Bill.objects.get(id=id_new_group_2[0])] 

добавил метод str(), т.е.

result_2 = [str(Bill.objects.get(id=result[0])), str(Bill.objects.get(id=result[1]))]
...  
end_player = [None, str(Bill.objects.get(id=id_new_group_2[0]))]

хотя не совсем понятно почему это пришлось делать, т.к. в модели уже указано, что должно выводить поле с именем

class Bill(models.Model):
    ...
    bill_fio = models.CharField(max_length=50, verbose_name='ФИО')
    ...
    def __str__(self):
             return "%s" % self.bill_fio

p.s.: а вообще был выбран не совсем правильный способ отправления в шаблон данных, т.к. делать это нужно, отправляя в шаблон объекты

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.