Как передать первичный ключ экземпляра из HTML в views.py? - PullRequest
0 голосов
/ 17 октября 2019

У меня есть следующая таблица экземпляров модели:

 _____________________
|1|    |    |    |<a/>|
 _____________________
|2|    |    |    |<a/>|
 _____________________
|3|    |    |    |<a/>|
.......................
 _____________________

Django генерирует ее с помощью for цикла шаблона, а первый столбец является первичным ключом экземпляра модели. Последний столбец представляет собой ссылку на страницу с формой редактирования этого экземпляра модели. У меня есть 2 функции в views.py: отображать эту страницу (edit_employee()) и отправлять изменения (edit_employee_action()). В последнем мне нужно обработать этот первичный ключ.

Здесь пользователь выбирает экземпляр

 <table>
        <tr>
            <th class="table-title" id="number">
                №
            </th>
            <th class="table-title" id="second-name">
                Фамилия
            </th>
            <th class="table-title" id="first-name">
                Имя
            </th>
            <th class="table-title" id="patronymic">
                Отчество
            </th>
            <th class="table-title" id="birth-date">
                Дата рождения
            </th>
        </tr>
        {% for employee in table %}
            <tr>
                {% for field in employee %}
                    <th>{{ field }}</th>
                {% endfor %}
                <th class="button-cell" id="edit"><a employee_id="{{ employee.0 }}" href="{% url 'edit-employee' %}">!</a></th>
                <th class="button-cell negative" id="delete"><a href="{% url 'delete-employee' %}">-</a></th>
            </tr>
        {% endfor %}
    </table>

Форма

  <form id="add-employee-form" action="edit/<int:id>/" method="POST">
        <table>
            <tr>
                <th class="table-title" id="second-name">
                    Фамилия
                </th>
                <th class="table-title" id="first-name">
                    Имя
                </th>
                <th class="table-title" id="patronymic">
                    Отчество
                </th>
                <th class="table-title" id="birth-date">
                    Дата рождения
                </th>
            </tr>
            <tr>
                <th id="second-name">
                    <div class="field-wrapper">
                        {{ form.second_name.errors }}
                        {{ form.second_name }}
                    </div>
                </th>

                <th id="first-name">
                    <div class="field-wrapper">
                        {{ form.first_name.errors }}
                        {{ form.first_name }}
                    </div>
                </th>

                <th id="patronymic">
                    <div class="field-wrapper">
                        {{ form.patronymic.errors }}
                        {{ form.patronymic }}
                    </div>
                </th>

                <th id="birth-date">
                    <div class="field-wrapper" id="birth-date-wrapper">
                        {{ form.birth_date.errors }}
                        {{ form.birth_date }}
                    </div>
                </th>
            </tr>
        </table>
        {% csrf_token %}

urls.py

    path('employee/edit_employee/', views.edit_employee, name='edit-employee'),
    path('employee/edit_employee/edit/', views.edit_employee_action, name='edit-employee-action'),

views.py

def edit_employee(request):
    form = AddEmployeeForm()
    return render(
        request,
        'edit_employee.html',
        context={'form': form}
    )

def edit_employee_action(request, id):
    if request.method == "POST":
        form = AddEmployeeForm(request.POST)
        if form.is_valid():
            edited_employee = .............
            edited_employee.update(
                first_name = request.POST.first_name,
                second_name = request.POST.second_name,
                patronymic = request.POST.patronymic,
                birth_date = request.POST.birth_date
            )
    else:
        form = AddEmployeeForm()
    form = AddEmployeeForm()
    return render(
        request,
        'edit_employee.html',
        context={'form': form}
    )
  • Как передать первичный ключ из HTML в views.py?
  • Как передать этот ключ из edit_employee() вedit_employee_action()? Я мог бы создать глобальную переменную, но я полагаю, это не лучший способ.

1 Ответ

1 голос
/ 17 октября 2019

Укажите параметр id в пути вашего представления в файле urls.py:

path('edit_employee_action/<int:id>/', views.edit_employee_action, name='edit_employee_action'),

Затем добавьте аргумент в ваше представление edit_employee_action:

from django.shortcuts import get_object_or_404
# your other imports...

def edit_employee_action(request, id):
    employee = get_object_or_404(YourModel, id=id)  # show a 404 error if the record doesn't exist.
    # the rest of your code

Наконец добавьте id к вашему тегу <a> в таблице:

...
<th class="button-cell" id="edit"><a method="post" href="{% url 'edit-employee' employee.id %}">!</a></th>
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...