Я хочу использовать .py файл в Django, но столкнулся с некоторыми проблемами. Я совсем новичок и мне нужно решение.
Я создал скрипт python для поиска маски подсети для заданного числа хостов. Но я хочу, чтобы он принимал HTML ввод по нажатию кнопки и передавал его как пользовательский ввод в скрипт python и выдавал результат на той же HTML странице. Я попытался дать вам, ребята, максимум деталей этой программы. Я не могу понять проблему. Он показывает, что принимает ввод в url, как здесь, вывод терминала для ввода 500
urls.py
path('findSM_H', views.findSM_H, name='findSM_H'),
path('findSM_Houtput', views.findSM_Hexecution, name='findSM_Houtput')
findSM_H.html
<form method="GET" action="/findSM_H">
{% csrf_token %}
<table>
<tbody>
<tr>
<td width="450">
<table width="450">
<tbody>
<tr>
\\TAKING INPUT FROM THE USER
<td width="250" height="50">
<label for="noofhostinput"> Number of host </label>
</td>
<td width="250" height="50">
//ON CLICKING THE BUTTON IT TAKES TO 'findSM_Houtput' FUNCTION
<input id="noofhostinput" type="text" name="noofhostinput" />
<input type="submit" onclick="location.href ='{%url 'findSM_Houtput'%}'" >
</td>
</tr>
</tbody>
</table>
</td>
<td width="30"></td>
<td width="450">
<table width="450">
<tbody>
<tr>
<td width="250" height="50">
//OUTPUT OF THE USER INPUT
<label for="subnetmask"> Subnet mask </label>
</td>
<td width="200" height="50">
<div id="subnetmask" style="background-color: ddb(39, 6, 39)" type="text">
00{{noofhost_op}}
</div>
<h3>0.{{noofhost_op}}</h3>
</td>
</tr>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
views.py
def findSM_H(request):
return render(request, 'findSM_H.html')
def findSM_Hexecution(request):
noofhost_input = request.GET.get("noofhostinput")
noofhost_output = run([sys.executable, 'D:\\Network_Project\\NetworkTools\\use_host_to_find_subnet_Mask_with_value.py',
noofhost_input], shell=False, stdout=PIPE)
print(noofhost_output)
return render(request, 'findSM_H.html', {'noofhost_op': noofhost_output})
use_host_to_find_subnet_Mask_with_value.py
import sys
noofhostinput="%s" % (sys.argv[1])
usr = int(noofhostinput)
table = [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,
32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216]
for i in table:
if usr < i:
n = table.index(i)
break
csm = 32- n
if csm >=8 or csm<33:
sm={'8':'255.0.0.0',
'9':'255.128.0.0',
'10':'255.192.0.0',
'11':'255.224.0.0',
'12':'255.240.0.0',
'13':'255.248.0.0',
'14':'255.252.0.0',
'15':'255.254.0.0',
'16':'255.255.0.0',
'17':'255.255.128.0',
'18':'255.255.192.0',
'19':'255.255.224.0',
'20':'255.255.240.0',
'21':'255.255.248.0',
'22':'255.255.252.0',
'23':'255.255.254.0',
'24':'255.255.255.0',
'25':'255.255.255.128',
'26':'255.255.255.192',
'27':'255.255.255.224',
'28':'255.255.255.240',
'29':'255.255.255.248',
'30':'255.255.255.252',
'31':'255.255.255.254',
'32':'255.255.255.255'}
for i in range(8,33):
if i == csm:
j= str(i)
output = f'your subnet mask for {usr} Host is {sm[j]}/{csm}'
print(output)
else:
output="your value is out of range of valid subnet mask."
print(output)
журнал терминала
[14/Feb/2022 05:45:30] "GET /findSM_H?csrfmiddlewaretoken=4SK8zRYZkwzVYb8RP80A8Wu3tILyhJGejbsAfKTHUAh9VgjGMfDdFjtSVFLexTlD&noofhostinput=500 HTTP/1.1" 200 4868Internal Server Error: /findSM_Houtput
Traceback (most recent call last):
File "C:\Users\NIRMAL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\NIRMAL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Network_Project\NetworkTools\NetworkApps\views.py", line 24, in findSM_Hexecution
noofhost_output = run([sys.executable, 'D:\\Network_Project\\NetworkTools\\use_host_to_find_subnet_Mask_with_value.py',
File "C:\Users\NIRMAL\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 505, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\NIRMAL\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\NIRMAL\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1360, in _execute_child
args = list2cmdline(args)
File "C:\Users\NIRMAL\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 565, in list2cmdline
for arg in map(os.fsdecode, seq):
File "C:\Users\NIRMAL\AppData\Local\Programs\Python\Python39\lib\os.py", line 822, in fsdecode
filename = fspath(filename) # Does type-checking of `filename`.
TypeError: expected str, bytes or os.PathLike object, not NoneType
[14/Feb/2022 05:45:30,806] - Broken pipe from ('127.0.0.1', 49451)
Ребята, что здесь не так, что пытается сказать django? любое предложение будет полезным
Вы можете проверить, пуст ли noofhost_input при отправке из браузера, потому что я думаю, что действие отправки ввода формы переписано (см. ниже):
def findSM_Hexecution(request):
noofhost_input = request.GET.get("noofhostinput")
print("******",noffhost_input,"*****")
noofhost_output = run([sys.executable, 'D:\\Network_Project\\NetworkTools\\use_host_to_find_subnet_Mask_with_value.py',
noofhost_input], shell=False, stdout=PIPE)
print(noofhost_output)
Полагаю, что noffhost_input пуст, потому что определение onclick перезаписывает действие формы, но не передает значения полей ввода формы.
<input type="submit" onclick="location.href ='{%url 'findSM_Houtput'%}'"
Кстати: действие формы указывает на другой адрес. Решение - убрать onclick... и направить действие формы на findSM_Houtput.