В django, как использовать данные другой модели из представлений на основе функций - PullRequest
0 голосов
/ 01 июня 2018

Итак, у меня есть форма, которая обновляет объект key_instance заемщиком.В настоящее время моему приложению требуется, чтобы пользователь ввел имя заемщика, но я хочу, чтобы оно отображало раскрывающийся список данных из другой модели, из которой выбирается модель user. Есть ли способ сделать это в представлении на основе классов?Вот мой views.py и мой шаблон.Я подумал о том, что я хотел бы использовать get_list_or_404 на модели пользователя и отобразить его в виде раскрывающегося списка в шаблоне и использовать этот выбор для заполнения поля формы.

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

Кто-нибудь знает, является ли это правильным способом или это выполнимо?Спасибо !!

views.py

def submit_key_request(request, pk):

    """
    View function for renewing a specific keyInstance by admin
    """
    key_inst=get_object_or_404(KeyInstance, pk=pk)
    names = get_list_or_404(Users)

    # If this is a POST request then process the Form data
    if request.method == 'POST':

        # Create a form instance and populate it with data from the request (binding):

        form = UpdateKeyForm(request.POST)


        # Check if the form is valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
            key_inst.is_requested = True
            key_inst.status = 'r'
            key_inst.date_requested = datetime.date.today()
            key_inst.borrower = form.cleaned_data['borrower']
            key_inst.save()

            # redirect to a new URL:
            return HttpResponseRedirect(reverse('all-available-keys') )


    # If this is a GET (or any other method) create the default form.
    else:

        form = UpdateKeyForm(initial={'borrower': 'N/A'})

    return render(request, 'catalog/keyinstance_request_update.html', {'form': form, 'keyinst':key_inst})

template

{% extends "base_generic.html" %}
{% block content %}
<div class="wrapper">

    <div class="centered"> <h1>Request Keys For Room: {{keyinst.roomkey}}</h1></div>



<div class="square-box">
    <div class="square-content">
    <form action="" method="post" >

        {% csrf_token %}
        <table style="display: inline-flex">
        {{ form}}
        </table>
        <select name = 'name'>
        {% for name in names %}
            <option value="{{ name }}">{{ name }}</option>
        {% endfor %}
        </select>
        <p>
            (Please use their login name i.e. <b>{{ user.get_username }}</b>)
        </p>
        <p><input required id="checkBox" type="checkbox" onclick="validate()"> I accept the <a href="{% url 'key-agreement'%}">terms and conditions</a></p>
        <p id="text" style="display:none">You Have Agreed To the Terms and Conditions</p>
        <input type="submit" value="Submit" />
    </form>
    </div>
</div>

</div>

{% endblock %}

1 Ответ

0 голосов
/ 01 июня 2018

Вот как мне удалось это сделать. Не уверен, что это лучший «питон» или лучшая практика.Пожалуйста, дайте мне знать, если это не так.

my views.py

def submit_key_request(request, pk):

    """
    View function for renewing a specific keyInstance by admin
    """

    key_inst=get_object_or_404(KeyInstance, pk=pk)
    names = get_list_or_404(User)

    # If this is a POST request then process the Form data
    if request.method == 'POST':
        name = request.POST['name']

        key_inst.is_requested = True
        key_inst.status = 'r'
        key_inst.date_requested = datetime.date.today()
        key_inst.borrower = name
        key_inst.save()

        return HttpResponseRedirect(reverse('all-available-keys') )


    # If this is a GET (or any other method) create the default form.
    else:
        pass


    return render(request, 'catalog/keyinstance_request_update.html', {'keyinst':key_inst, 'names':names})

template

{% extends "base_generic.html" %}
{% block content %}
<div class="wrapper">

    <div class="centered"> <h1>Request Keys For Room: {{keyinst.roomkey}}</h1></div>



<div class="square-box">
    <div class="square-content">
    <form action="" method="post" >

        {% csrf_token %}
        </br>
        <select name = 'name' required>
        {% for key in names %}
            <option value="{{ key }}">{{ key }}</option>
        {% endfor %}
        </select>

        <p>
            (Please use their login name i.e. <b>{{ user.get_username }}</b>)
        </p>
        <p><input required id="checkBox" type="checkbox" onclick="validate()"> I accept the <a href="{% url 'key-agreement'%}">terms and conditions</a></p>
        <p id="text" style="display:none">You Have Agreed To the Terms and Conditions</p>
        <input type="submit" value="Submit" />
    </form>
    </div>
</div>

</div>

{% endblock %}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...