Django: search_device_list () отсутствует 1 обязательный позиционный аргумент: 'id' - PullRequest
0 голосов
/ 28 марта 2020

У меня есть поисковая страница, которая работала, пока я не закодировал возврат поиска для редактирования. В идеале, пользователь выполняет поиск, и он возвращает некоторые значения, пока все хорошо. Затем, когда пользователь нажимает на кнопку редактирования значения, я хочу, чтобы поля возвращались в редактируемом формате.

Вот views.py

def search_device_list(request, id):
     license_key = Maintenance.objects.get(id=id)
     maintenance_form = MaintenanceForm(instance=license_key) 
     devices = Devices.objects.filter(maintenance = id)
     end_of_maintenance_support = MaintenanceForm()

     locations = Locations.objects.all()
     context ={"locations": locations}

     for locations in context['locations']:
        print(locations)

     if request.method == 'POST':
         location_name=request.POST.get('location_name')
         my_devices = Devices.objects.filter(locations = Locations.objects.get(location_name = location_name))
         maintenance_form = MaintenanceForm(request.POST, instance=license_key)
         license_key = request.POST.get('license_key')
         maintenance_support_end_date = request.POST.get('maintenance_support_end_date')

         context["devices"]= my_devices   
         context["location_name"]= location_name  
         context["license_key"] = license_key
         context["maintenance_support_end_date"] = maintenance_support_end_date

         if maintenance_form.is_valid(): 
            license = maintenance_form.save()
            print (license.license_key)

            postdevices= request.POST.getlist("devices")
            for device_hostname in postdevices:
                device = Devices.objects.get(device_hostname = device_hostname)
                print(device.maintenance.license_key)
                print(device.maintenance.maintenance_support_end_date)
                device.save()

     return render(request, 'inventory/search_device_list.html', context)  

Вот template.py

{% block content %} 

<h2 align="left">Search Page</h2>

<!-- <form action="{% url 'inventory:render_results' %}" method="POST" > -->
<form action="{% url 'inventory:search_device_list' %}" method="POST" >

{% csrf_token %}  
<body>
<table class=table> 
<tr>
    <td><b>Locations: &nbsp;&nbsp; </b></td>
    <td>
    <select name="location_name">
    {% for locations in locations %} 
    <option value="{{locations.location_name}}">{{locations.location_name}}</option>{% endfor%}
    </select>
    </td>
    <td><input type="submit" name = "submit" value="Submit"/></td>
</tr>
<br>

<h3 align="left">Render Device List based on Location Choice</h3>
<table>
    <tr>
        <td><b>Locations:</b><br>{{location_name }} <br></td>
        <td><b> Devices: </b><br>
        {% for device in devices %}{{device.device_hostname}} <br>{% endfor %}  </td>

        <td id="maintenance_support_end_date"><b>End of Maintenance Support:</b><br>{% for device in devices%}{{device.maintenance.maintenance_support_end_date}}<br> {% endfor %}  </td>   
        <td id="license_key"><b>License Key:</b><br>{% for device in devices%}{{device.maintenance.license_key}}<br>{% endfor %}</td>
        <td><b>Actions:</b><br> {% for device in devices%} <a href= {% url 'inventory:search_device_list' %}><button id="maintenance_support_end_date">Edit </button></a><br> {% endfor %}  </td>   

    </tr>   
</table>

<table class=table> 
<h3 align="left"> Edit Table </h3>
<tr>
    <td><b>Locations:&nbsp;</b></td><td>{{maintenance_form.location_name}}</td>
    <td><b>Devices&nbsp;</b></td><td>{% if devices %} 
                {% for device in devices %} 
                    {{ device }} <br><br> 
                {% endfor %} </td>
    <td><b>License Key:&nbsp;</b></td><td>{{maintenance_form.license_key}}</td>
    <td><b>Support End Date:&nbsp;</b></td><td>{{maintenance_form.maintenance_support_end_date}}</td>   
</tr>
</table>

 {% endblock content %}

И, наконец, urls.py - я сделал несколько поисков по этому сообщению об ошибке, так как оно является обычным, поэтому я попробовал два разных пути URL

     url(r'^search_device_list/$', views.search_device_list, name='search_device_list'), 
     url(r'^search_device_list/(?P<id>\d+)$', views.search_device_list, name='search_device_list'), 

Два здесь упоминаются разные модели, устройства и техническое обслуживание. И я думаю, что это недостаток в моем понимании того, как идентификатор передается через код. Любые идеи или советы приветствуются.

1 Ответ

0 голосов
/ 28 марта 2020

Решение

Изменить

def search_device_list(request, id):

На

def search_device_list(request, id=None):

Обратите внимание, что вам придется изменить ваш код, так что он обрабатывает случай, когда id равен None, как в настоящее время, ваше представление зависит от того, что дано id.

Пояснение

И /search_device_list/, и /search_device_list/(?P<id>\d+) используют одно и то же представление.

Когда вы получаете доступ к первому URL, он вызывает функцию просмотра, но не передает id.

Когда вы получаете доступ к /search_device_list/(?P<id>\d+), он вызывает вашу функцию просмотра, но на этот раз он проходит id.

Изменяя функцию просмотра на def search_device_list(request, id=None):, вы делаете необязательный параметр id вашей функции просмотра

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