我怎么能运行在一个按钮preSS不呈现内容的Django的功能? [英] How can I run a Django function on a button press which doesn't render content?

查看:128
本文介绍了我怎么能运行在一个按钮preSS不呈现内容的Django的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我过得好得很好,Django的&放大器; Python的,只是得到了搜索功能的工作。但我不能确定我的下一个问题。

I'm getting on quite well with Django & Python, just got a search function working. But I'm unsure of my next problem.

我有一个功能,连接到Amazon S3和存储密钥在我的数据库。我目前运行这个当页面呈现,但我想是有它运行该呼叫按钮,它会像一个刷新按钮来更新最新的内容数据库。

I've got a function that connects to Amazon S3 and stores keys in my database. I currently run this when a page renders, but what I want is to have a button which runs this call so it'll be like a refresh button to update the database with the latest content.

在搜索行动去 /搜索/ 这样的URL照顾给了一个模板,以便运行搜索code。但是,如果我更新的形式有行动=。并应更改页面,你怎么点它的功能? (我使用的是通用的看法)

The action on search goes to /search/ so urls takes care of giving that a template and a view to run the search code. But if my update form has action="." and should change the page, how do you point it to the function? (I'm using generic views)

这很可能是使从功能到屏幕上的结果是个好主意,但我首先只是想了解你如何调用一个函数,并不一定表明该用户任何东西。

It'd probably be a good idea to render results from the function to the screen, but I first just want to understand how you call a function that doesn't necessarily show the user anything.

我的功能是相当简单(是的,我添加了第一个if语句,因为我尝试实现这一点):

My function is fairly simple (and yes, I've added that first if statement as I try to implement this):

def updateRevFromS3(request):
if ('r' in request.POST) and request.POST['r'].stript():
    s3 = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) # Connect to Amazon S3
    b = s3.get_bucket(settings.AWS_STORAGE_BUCKET_NAME) # Find existing bucket to store data
    revision = b.list(prefix="{{ update_revision }}")

    for key in revision:
        # download values to db
        try:
            obj = screenshots.objects.get(imgUrl=key.name, mod_date=key.last_modified)
        except screenshots.DoesNotExist:            
            obj = screenshots(  imgUrl = key.name,
                                meta = key.metadata,
                                mod_date = key.last_modified)
            obj.save()
            print "Saving: " + key.name         
        else:
            print key.name + " already exists."

和我的方式:

<form action="." method="get" id="updateForm">{% csrf_token %}
   <label>Update images for revision:</label><br/>
   <input type="text" name="r" value="{{ update_revision|escape }}"/> 
   <input type="submit" value="Update" />
</form>

下一步将是向用户提供一些反馈结果,但我会坐上去后,我可以调用的功能!感谢:)

The next step would be to give the user some feedback as a result, but I'll get on to that after I can call the function! Thanks :)

更新

我已经把一些JQ在赶更新的形式(我把警报在测试此);

I've put some jQ in to catch the update form (I put an alert in to test this);

<script type="text/javascript">
        $("#updateForm").bind("submit", function(){
            $.post(ajax_url, {r: $(this).find('[name="r"]').val()}, function(data){
                // nothing here for now, but this is where you could update the UI, etc. 
            });
            return false;
        });
    </script>

和我的默认视图如下(本总是通过最后的回报下降);

And my default view is as follows (this always falls through the final return);

def index(request):
if request.is_ajax():
    print "is ajax"
    return updateRevFromS3(request)
elif request.POST.get('r') == "updateForm":
    print "is post"
    return updateRevFromS3(request)
print "not ajax or post"
return render_to_response("base.html", RequestContext(request))

我已经不知道我真的有这个做看作是思想,我不知道为什么我的控制台窗口中显示GET和每个页面加载POST请求。如果多数民众赞成的情况下,为什么不索引视图返回updateRevFromS3功能?

Seen as thought I've not idea what I'm really doing with this, I'm not sure why my console window shows GET and POST requests on each page load. If thats the case why doesn't the index view return the updateRevFromS3 function?

推荐答案

如果您使用的是正常的表单POST,该页面将重新加载 - 这是多么HTTP工作。有一个'背景'POST,你需要使用AJAX。如果您有jQuery的网页上,你会想要一个ID添加到您的形式,因此它可以很容易地选择,然后做一些事情是这样的:

If you use a normal form POST, the page will reload - that's just how HTTP works. To have a 'background' POST, you need to use AJAX. If you have jQuery on your page, you'll want to add an ID to your form so it can be easily selected, then do something like this:

$("#formid").bind("submit", function(){
    $.post(ajax_url, {r: $(this).find('[name="r"]').val()}, function(data){
        // nothing here for now, but this is where you could update the UI, etc.
    });
    return false;
});

下面是href="http://api.jquery.com/submit/" rel="nofollow">的

Here are the relevant jQuery docs.

在您看来,您可以有条件地调度的基础上清爽的功能request.is_ajax()(或任何其他条件,比如,无论是通过提供一个特定职位的关键一个隐藏的输入是present):

In your view, you can conditionally dispatch to the refreshing function based on request.is_ajax() (or any other condition, say, whether a particular POST key provided by a hidden input is present):

def your_view(request):
    if request.is_ajax(): return updateRevFromS3(request)
    elif request.POST.get("my-hidden-input-name") == "this-is-the-update-form":
        return updateRevFromS3(request)
    return normal_processing()

这篇关于我怎么能运行在一个按钮preSS不呈现内容的Django的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆