在django应用程序中重定向url的好方法

时间:2013-06-18 14:10:00

标签: python django

我正在构建一个Django应用程序,我有一个主页面链接到不同的URL来执行操作(例如,有一个链接将数据添加到数据库)。这是使用模板中的表单完成的,并将当前URL从app / index更改为app / add。问题是,当我在管理该操作的脚本中使用render_to_response时,它不会更改URL,但它会将正在使用的html更改回索引页面。因此,如果您使用应用程序中的链接,但是如果用户在任何时候尝试刷新其中一个页面,它可能会再次执行操作(即如果您刷新应用程序/添加它将再次添加该记录)。我会使用HttpResponseRedirect或重定向,但我需要传递一个包含jobList的上下文(无论我在哪里使用render_to_response,请参见下文)。我目前的解决方法是将所有操作都集中到索引页面的脚本中,并将所有操作按钮重定向到提交的选项,但这是构建程序的一种可怕方式,我觉得必须有更好的方法这个。希望这不是太多的文字。作为参考,这里有几个相关的文件。提前感谢您的帮助。

urls.py

from django.conf.urls import patterns, include, url
from django.views.generic import DetailView, ListView
from django.conf.urls.defaults import *
from Minion.models import Job

urlpatterns = patterns('Minion.views',
    # URLs for the MinionUI app
    url(r'^$', 'home'),
    url(r'^index/$', 'detail'),
    url(r'^add/$', 'add'),
    url(r'^output/$', 'output'),
    url(r'^change/$', 'change'),
    url(r'^cal/$', 'calendarTest'),
    url(r'^delete/$', 'delete'),
    url(r'^change/$', 'change'),
)

views.py(只有部分内容,不要让屏幕太杂乱)

#This script is responsible for whatever operations need to happen before viewing the index page again and then displaying the index page
#This includes:
#user authentication
#adding entries to the database
def detail(request):
    if request.user.is_authenticated():
        if 'isAdding' in request.POST:
            #Add data to database
            job = Job()
            job.name = request.POST['name']
            job.user = request.POST['user']
            job.command = request.POST['command']
            job.ipRange = request.POST['ipRange']
            job.whenToRun = str(request.POST['dateToRun']) + ' ' + str(request.POST['timeToRun'])
            job.save()
        elif 'isChanging' in request.POST:
            #Change selected data in database
            job = Job()
            job.name = request.POST['name']
            job.user = request.POST['user']
            job.command = request.POST['command']
            job.ipRange = request.POST['ipRange']
            job.whenToRun = str(request.POST['dateToRun']) + ' ' + str(request.POST['timeToRun'])
            job.save()
        jobList = Job.objects.all()
        return render_to_response('Minion/detail.html', {'jobList': jobList}, context_instance=RequestContext(request))
    else: #need to authenticate user
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    jobList = Job.objects.all()
                    return render_to_response('Minion/detail.html', {'jobList': jobList}, context_instance=RequestContext(request))
                else:
                    return render_to_response('Minion/home.html', {'loginFail': True}, context_instance=RequestContext(request))
            else:
                return render_to_response('Minion/home.html', {'loginFail': True})
        else:
            return render_to_response('Minion/home.html', {'improperURL': True}, context_instance=RequestContext(request))

detail.html(主索引模板)

{% load i18n %}
<head>
    <!script src="//ajax.googleapis.com/ajax/libs/jquery/jquery.min.js" />
    <script type="text/javascript">

        //These two function are used to change where we direct our POST data to
        function determineWhereToGo(){
            try{
                var element = document.getElementById('dropdown');
                var selected = element.options[element.selectedIndex].text;
                if(selected === "Delete"){
                    document.getElementById('checkboxes').action = "{% url 'Minion.views.delete' %}";
                }else if(selected === "Change"){
                    document.getElementById('checkboxes').action = "{% url 'Minion.views.change' %}";
                }
            }catch(err){
                alert("Javascript Error\n" + err.message);
            }
        }
    </script>
</head>
<table border="2">
    <tr>
        <th />
        <th>Job ID</th>
        <th>Name</th>
        <th>User</th>
        <th>Command</th>
        <th>IP Range</th>
        <th>Date to Run</th>
    </tr>
    <form id="checkboxes" method="post" action="{%url 'Minion.views.detail' %}">
        {% csrf_token %}
        {% for job in jobList %}
            <tr>
                <td><input type="checkbox" name="{{ job.id }}Selection"/></td>
                <td>{{ job.id }}</td>
                <td>{{ job.name }}</td>
                <td>{{ job.user }}</td>
                <td>{{ job.command }}</td>
                <td>{{ job.ipRange }}</td>
                <td>{{ job.whenToRun }}</td>
            </tr>
        {% endfor %}
        <select id="dropdown" onchange="determineWhereToGo();">
            <option />
            <option value="Delete">Delete</option>
            <option value="Change">Change</option>
        </select>
        <input type="submit" value="Go" />
    </form>
    <form method="post" action="{% url 'Minion.views.add' %}">
        {% csrf_token %}
        <input type="submit" value="Add" />
    </form>
</table>

add.html(这是一个使用isAdding选项供参考的模板)

{% load i18n %}

<h1>Add a Job</h1>
<hr width="18%" size="3" align="left" />
<form method="post" action="{% url 'Minion.views.detail' %}">
{% csrf_token %}
    Name<input type="text" name="name" /><br /><br />
    User<input type="text" name="user" /><br /><br />
    Command<input type="text" name="command" /><br /><br />
    IP Range<input type="text" name="ipRange" /><br /><br />
    Date to Run<input type="date" name="dateToRun" value="YYYY-MM-DD" /><br /><br />
    Time to Run<input type="time" name="timeToRun" value="HH:MM:SS" /><br /><br />
    <input type="hidden" name="isAdding" value="True" />
    <input type="submit" value="Add Job" />
</form>

0 个答案:

没有答案