在httpd服务器上运行时,无法找到Django项目请求的URL?

时间:2018-04-05 11:21:16

标签: javascript jquery ajax django

这篇文章有点长。那些感兴趣的人请耐心等待。 我在apache2服务器上运行Django项目。 我在index.html HTML页面中的锚标记中嵌入了两个图像:

<a id="pop1" href="#"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSuFkPwpxwXwgnnwvPHLxW1sCbtPKfqdpz6jApGYbEbeD99Ob-Z" width="30px" height="25px" style="margin-bottom:6px;"> </a>

<a align="right" id="pop2" href="#"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSuFkPwpxwXwgnnwvPHLxW1sCbtPKfqdpz6jApGYbEbeD99Ob-Z" width="30px" height="25px" style="margin-bottom:6px;"> </a>

当我点击图像时,都会打开相同的模态框。以下是模态框代码:

 <div id="alarmModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Shutdown Machines with less than certain % CPU Utilization after N minutes</h4>
            </div>
            <div class="modal-body">
                <p> Please fill in the specifics below:</p>
                         <form id="alarm_form" action="/create_alarm/" method="POST">{% csrf_token %}
                               <label for="period">Period of inactivity(in minutes):</label>
                              <input type="number" id="period" min="0" max="60" step="5" required>
                               <label for="cpu">CPU Utilization(in %):</label>
                              <input type="number" id="cpu" min="0" max="100" step="1" required>
            <br>
               <div id="alarmresult"></div>
            </div>
            <div class="modal-footer">
                <input class="btn btn-default" id="upload" type="submit" value="Optimize"></input>
                </form>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
               </div>
            </div>
        </div>
    </div>

我的Ajax和Jquery代码粘贴在下面:

function alarmfunc(){
//$('#pop1,#pop2').on('click', function(event){
//$('#alarmModal').modal('show');

//Submit Post on Submit

$('#alarm_form').on('submit', function(event){
 event.preventDefault();
$('#optimize').attr("disabled",true);
 console.log("form submitted!");
 var period = $("#period").val();
 var cpu = $("#cpu").val();
 console.log(period,cpu)
//alert(form_data);
 $.ajax({
  url : "/cloud_alarm/",
  type : "POST",
  data : {period:period, cpu:cpu},
  cache: false,
 //handle a successful response
  success : function(result) {
      $("#alarmresult").empty();
      $('#optimize').removeAttr("disabled");
      console.log("success");
      $("#alarmresult").prepend("<br><p><span class='title'>CloudWatch Alarm Status: " + result + "</span></p>");
   },

 //handle a non-successful response
 error : function(xhr,errmsg,err) {
       $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
            " <a href='#' class='close'>&times;</a></div>");
       console.log(xhr.status + ": " + xhr.responseText);
  }
});
});
}
} 

在我的urls.py中,我粘贴了以下网址:

 url(r'^home(?P<uid>[a-zA-Z0-9]{0,20})/cloud_alarm/', views.cloud_alarm, name="cloudalarm"),

最后我的views.py函数如下:

def cloud_alarm(request,uid):
  if request.method == 'POST':
    period = request.POST['period']
    #ins_id = request.POST['insid']
    cpu = request.POST['cpu']
    period = int((period) * 60)
    starter_pack_accnum =293952640683
    try:
      cloudwatch=boto3.client('cloudwatch',region_name='us-west-2')
      cloudwatch.put_metric_alarm(
       AlarmName='Alarm_'+ str(insid),
       ComparisonOperator='LessThanThreshold',
       EvaluationPeriods=5,
       MetricName='CPUUtilization',
       Namespace='AWS/EC2',
       Period= period,
       Statistic='Average',
       Threshold=30.0,
       ActionsEnabled=True,
       AlarmDescription='Alarm when server CPU falls below 30%',
       Dimensions=[
       {
        'Name': 'InstanceId',
        'Value': ins_id
       },
      ],
       AlarmActions=['arn:aws:swf:us-west-2:' + str(starter_pack_accnum) + ':action/actions/AWS_EC2.InstanceId.Stop/1.0'],
       Unit= 'Percent',
       )
      result = "The CloudWatch Alarm," + str(AlarmName) + "has been created for this instance for the optimization process."
    except Exception as e:
      result = "An unexpected error occurred while creating the CloudWAtch alarm" + str(AlarmName) + "for this instance."

   return HttpResponse(result)

但是当我尝试提交表单时,它会重定向到:         &#34; 找不到请求的网址&#34;

我在这里做错了什么?将值从模态形式传递给ajax是否存在问题?我是一个小小的初学者。任何帮助将不胜感激。 请帮忙。

2 个答案:

答案 0 :(得分:0)

您未提交更正网址的请求 更改代码如下例所示。它会工作。

<强> urls.py

 url(r'^cloud_alarm/$', views.cloud_alarm, name="cloudalarm"),

<强> views.py

def cloud_alarm(request):
   # your code

答案 1 :(得分:0)

尝试更改表单:

<form id="alarm_form" action="/create_alarm/" method="POST">

为:

<form id="alarm_form" action="{% url 'app_name:cloudalarm' uid %}" method="POST">

看起来你的表单动作没有通过uid。我不知道您在urls.py中定义了哪些 app_name ,因此您需要将“app_name”更改为您的appname。确保您在urls.py中定义了应用名称,如here所示。