2

我有一个带有姓名、年龄、电子邮件字段的学生模型。我为此创建了一个 StudentForm 表单,并创建了一个这样的视图

def student(request):
form=Studentform(request.POST)
if request.method=='POST':

    if form.is_valid():
        stu=Student()
        stu.name=form.cleaned_data['name']
        stu.email=form.cleaned_data['email']
        stu.age=form.cleaned_data['age']
        stu.save()

        return HttpResponseRedirect('/index/')

else:
    form=Studentform()
return render_to_response('index.html',{'form':form},context_instance=RequestContext(request) )

这里是我的 index.html

<html>
   <head>
   <title></title>
    <script type="text/javascript">
    var student={{ stu_var }}
    alert("erer")
     </script>
  </head>
  <body>

   <form action="/index/" method="post">{% csrf_token %}
       {{form.as_p}}
        <input type="submit" id="submit" name="submit" onclick="alert(student)">
      </form>
     </body>
</html>

现在我希望我在我的学生视图中创建一个 json 响应,其中包含学生对象的所有值并在发布时将其呈现到我的 index.html 中,这样我就可以生成一个警报,例如--->“Aditya Singh,你已成功提交数据”。其中 Aditya Singh 将是 django.thanx 的新学生的名字,因为你的宝贵回应

4

1 回答 1

1

因此,您希望在成功保存后查看已保存的学生数据……您不需要 javascript/json。

在您的代码中,保存信息后,您将用户重定向到“索引”视图。相反,您可能希望重定向到“成功!” 页面,您在其中显示信息:

HttpResponseRedirect('/success/%d/' % stu.id)

因此现有视图可能如下所示:

def student(request):

    form=Studentform(request.POST)

    if request.method=='POST':

        if form.is_valid():

            stu=Student()
            stu.name=form.cleaned_data['name']
            stu.email=form.cleaned_data['email']
            stu.age=form.cleaned_data['age']
            stu.save()

            return HttpResponseRedirect('/success/%d/' % stu.id)
        else:
            pass
            # return the half-completed form with the old data so the
            # user can make corrections
            # this "else" is not required, I just put it in here
            # to have a place to put this comment
            # and to show that this is another path that might be taken
            # through the code.

    else:
        # empty form for the user to fill out
        form=Studentform()

    return render_to_response('index.html',
        {'form':form},
        context_instance = RequestContext(request) )

您将为成功页面添加一个视图(也是相应的模板和 url 条目):

def success (request, id=None):

    stu = Student.objects.get (id = id)

    return render_to_response ('success.html',
        {'stu', stu},
        context_instance = RequestContext(request) )

如果你真的想要一个“警报”对话框,你可以为此创建一个 onLoad 事件。

如果要警告对话框索引页,那就有问题了。视图只能返回一件事,而您已经在返回索引页面。您必须以某种方式告诉索引页面要获取有关哪个学生的信息,但索引页面并不是真正为此设计的(假设您使用的是 Django 教程中的“索引”页面,没有表格的模型列表) .

许多网站所做的是将新创建的用户放在他们的个人资料页面上,如果他们成功创建了一个帐户。这样他们就可以确认他们已成功登录,并且他们准备好做一些有用的事情,而不是查看“成功”页面。

或者,他们将这个人放在网站的主页上,但这个人的登录名在导航栏中。这假定他们已登录并已注册。

于 2013-06-19T00:54:56.823 回答