简体   繁体   English

Django url重写并从Javascript传递参数

[英]Django url rewrites and passing a parameter from Javascript

As a bit of a followup question to my previous , I need to pass a parameter to a view. 作为我之前的一个后续问题,我需要将参数传递给视图。 This parameter is not known until the JS executes. 在JS执行之前,不知道该参数。

In my URLConf: 在我的URLConf中:

url(r'^person/device/program/oneday/(?P<meter_id>\d+)/(?P<day_of_the_week>\w+)/$',
therm_control.Get_One_Day_Of_Current_Thermostat_Schedule.as_view(), 
name="one-day-url"),

I can pass it this URL and it works great! 我可以传递这个URL,它很棒! ( thanks to you guys). (谢谢你们)。

http://127.0.0.1:8000/personview/person/device/program/oneday/149778/Monday/

In My template I have this: 在我的模板中,我有这个:

var one_day_url = "{% url personview:one-day-url meter_id=meter_id day_of_the_week='Monday' %}";

In my javascript: 在我的javascript中:

 $.ajax({
        type: 'GET',
        url: one_day_url ,
        dataType: "json",
        timeout: 30000,
        beforeSend: beforeSendCallback,
        success: successCallback,
        error: errorCallback,
        complete: completeCallback
    });

When this triggers it works fine except I dont necessarily want Monday all the time. 当这触发它工作正常,除了我不一定想要周一。

If I change the javascript to this: 如果我将javascript更改为:

var one_day_url = "{% url personview:one-day-url meter_id=meter_id %}";

and then

$.ajax({
        type: 'GET',
        url: one_day_url + '/Monday/',
        dataType: "json",
        timeout: 30000,
        beforeSend: beforeSendCallback,
        success: successCallback,
        error: errorCallback,
        complete: completeCallback
    });

I get the Caught NoReverseMatch while rendering error. 我在渲染错误时得到了Caught NoReverseMatch。 I assume because the URLconf still wants to rewrite to include the ?P\\w+) . 我假设因为URLconf仍然想要重写以包含?P \\ w +)。

I seems like if I change the URL conf that breaks the abailty to find the view , and if I do what I do above it gives me the NoREverseMatch error. 我好像如果我改变了破坏abailty的URL conf来查找视图,如果我做我上面做的事情,它会给我NoREverseMatch错误。

Any guidance would be appreciated. 任何指导将不胜感激。

I usually do something along the lines of 我通常会做一些事情

var one_day_url = "{% url personview:one-day-url meter_id=meter_id day_of_the_week='REPLACE_ME' %}";
// ...
url: one_day_url.replace('REPLACE_ME', 'Sunday')

you may want to use this kind of project which is meant to answer to this precise question... 您可能想要使用这种旨在回答这个精确问题的项目......

notice: it may help hacker to map the website: https://github.com/Dimitri-Gnidash/django-js-utils 通知:它可以帮助黑客映射网站: https//github.com/Dimitri-Gnidash/django-js-utils

When I don't use this project I put a default value in the url and replace it by correct value. 当我不使用这个项目时,我在网址中输入了一个默认值,并用正确的值替换它。

so use a complete reverse then: 所以使用完全反向然后:

url: one_day_url.replace('/Monday/','/Caturday/')

and even if you replace monday by monday it will works... 即使你在星期一取代星期一它也会起作用......

note: this ugly haks will fail if your default value is already sooner in the url so use it consequently. 注意:如果您的默认值已经在网址中提前,那么丑陋的黑客将会失败,因此请使用它。

I had a similar question. 我有一个类似的问题。 I wanted to open a URL when someone clicked a button. 我想在有人点击按钮时打开一个URL。 For what it's worth, here is how I handled this situation. 对于它的价值,这是我如何处理这种情况。

Define the URL as an attribute: 将URL定义为属性:

{% for article in articles %}    
  <button data-article-url="{% url view_article article.id %}">
    Read Article #{{ article.id }}
  </button>
{% endfor %}

Using jQuery, read the attribute and carry on: 使用jQuery,读取属性并继续:

var article_url = $(this).attr("data-article-url");

$.ajax({
  url: article_url,
  ...
});

You could use tokens in your url and pass it as a variable to your module: 您可以在网址中使用令牌并将其作为变量传递给您的模块:

<script src="{{ STATIC_URL }}js/my-module.js"></script>
<script>
$(function(){
    MyModule.init(
        "{% url personview:one-day-url meter_id='0000' day_of_the_week='{day}' %}"
    );
});
</script>
// js/my-module.js
var MyModule = {
    init: function(one_day_url) {
        var id = 1, day = 'Saturday';
        this._one_day_url = one_day_url;
        console.log(this.one_day_url(id, day));

        $.ajax({
            type: 'GET',
            url: this.one_day_url(id, day),
            dataType: "json",
            timeout: 30000,
            beforeSend: beforeSendCallback,
            success: successCallback,
            error: errorCallback,
            complete: completeCallback
        });
    },
    one_day_url: function(meter_id, day) {
        return this._one_day_url.replace('0000', meter_id).replace('{day}', day);
    }
};

Notice that token should match the regex type to resolve successfully (I can't use {meter_id} because it's defined with \\d+ ). 请注意,令牌应与正则表达式类型匹配才能成功解析(我不能使用{meter_id}因为它是用\\d+定义的)。

I'm a little bit unsatisfied with this solution and I ended by writing my own application to handle javascript with django: django.js . 我对这个解决方案有点不满意,最后我编写了自己的应用程序,用django: django.js来处理javascript。 With this application, I can do: 有了这个应用程序,我可以做到:

{% load js %}
{% django_js %}
{% js "js/my-module.js" %}
// js/my-module.js
var MyModule = {
    init: function() {
        var id = 1, day = 'Saturday';

        console.log(
            Django.url('personview:one-day-url', id, day),
            Django.url('personview:one-day-url', [id, day]),
            Django.url('personview:one-day-url', {
                meter_id: id,
                day_of_week: day
            })
        );

        $.ajax({
            type: 'GET',
            url: Django.url('personview:one-day-url', id, day),
            dataType: "json",
            timeout: 30000,
            beforeSend: beforeSendCallback,
            success: successCallback,
            error: errorCallback,
            complete: completeCallback
        });
    }
};

$(function(){
    MyModule.init();
});

Why not just pass them in as part of the request data. 为什么不直接将它们作为请求数据的一部分传递。 You can use the jQuery get function and pass them in as paramaters. 您可以使用jQuery get函数并将它们作为参数传递。

$.get("{%url personview%}", {'meter_id':"meter_id", "day_of_the_week":"monday" ...}, function(){do stuff when info is returned});

Then in your view you can do: 然后在您的视图中,您可以:

meter = request.GET['meter_id']

This will allow you to use it in your view. 这将允许您在视图中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM