1

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

网址.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>
4

0 回答 0