【问题标题】:how to create a function update using django and ajax如何使用 django 和 ajax 创建函数更新
【发布时间】:2019-11-29 14:50:10
【问题描述】:

我有一个 django 项目,其中包含一个表单,用户可以在其中插入数据并使用 django 函数和 ajax 调用将其保存到数据库中。

在 django 中不使用 ModelForm

现在我想允许用户更新他选择的表单,一旦用户选择表单,字段必须显示现有数据。

到目前为止,这是创建过程。

我知道更新过程需要对象的 id 才能更新选定的记录。

错误:

'suspect' 对象不可迭代请求方法:GET 请求 网址:http://127.0.0.1:8000/blog/update/23/ Django 版本:2.1.3 异常类型:TypeError 异常值:“怀疑”对象不是 可迭代异常位置:C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\defaulttags.py 在渲染中,第 165 行 Python 可执行文件:C:\Users\LT GM\AppData\Local\Programs\Python\Python37\python.exe

urls.py

 path('update/<int:pk>/',update,name = 'update'),

update.html

{% extends "base.html" %}
{% load static %}
{% block body %}


<head>
  <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}">
  <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}">
  <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}">
  <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}">
  <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}">
  <meta name= "viewport" content="width=device-width, initial-scale=1.0">
  <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script>
  <title>Welcome</title>
</head>
<body>


  <div class="lines">
  <div class="line"></div><div class="line"></div>
  <div class="line"></div><div class="line"></div>
  <div class="line"></div><div class="line"></div><div class="line"></div>
  </div>

  {% for suspect in instance %}
        <form enctype="multipart/form-data">
    <div id='left-column-Input' class="formInput" include="select()"> 
      <div class="forminputs">
        <input type="text" id="fname" name="fname" autocomplete="off" required />
          <label for="fname" class="label-name">
            <span class="content-name" name="fname">{{suspect.suspect_name}}</span>
          </label>
      </div>

    <div class="forminputs">
      <input type="text" id="lname" name="lname" autocomplete="off" required />
      <label for="lname" class="label-name">
        <span class="content-name" name="lname">{{suspect.suspect_last_name}}</span>
      </label></div>
    <div class="forminputs">
      <input type="text" id="fatherName" name="fatherName" autocomplete="off" required />
      <label for="fatherName" class="label-name">
        <span class="content-name" name="fatherName">{{suspect.suspect_father_name}}</span>
      </label></div>
    <div class="forminputs">
      <input type="text" id="motherName" name="motherName" autocomplete="off" required />
      <label for="motherName" class="label-name">
        <span class="content-name" name="motherName">{{suspect.suspect_mother_name}}</span>
      </label></div>
    <div class="formSelect">
      <select id="gender" name="gender" required>
        <option value="">{{suspect.gender}}</option>
        <option value="1">male</option>
        <option value="2">female</option>
      </select></div>
    <div>
      <textarea id="content" name="textarea" class="textArea" placeholder="content">{{suspect.content}} </textarea>
    </div>
    <div class="home-Button">
      <button id="edit" name="edit" type="submit">Edit</button>
      <button id="clear" name="clear" type="submit">Clear</button>
    </div>
    </div>

{% endfor %}

  <script type="text/javascript">
    $(document).ready(function(){                           
      $("#edit").on('click',function(event){
        event.preventDefault()
        fName=$('#fname').val()
        lName = $('#lname').val()
        fatherName = $('#fatherName').val()
        motherName = $('#motherName').val()
        gender = $('#gender').val()
        content=$('#content').val()

        $.ajax({
              url:'/blog/update',
              method:'POST',

          data: {
                FName: fName,
                LName: lName,
                FatherName: fatherName,
                MotherName: motherName,
                Gender: gender,
                content:content,

                // data:data
              },

              headers:{
                'X-CSRFToken':'{{csrf_token}}'
            }
          }).done(function(msg){
              location.href='/blog/list'
          }).fail(function(err){
            alert(err)
        })
      })
    })
  </script>
</form>

</body>
{% endblock %}

views.py

   def update(request,pk):
   #deny anonymouse user to enter the  detail page
    if not request.user.is_authenticated:
            return redirect("login")
    else:
      suspect = get_object_or_404(suspect, pk=pk)
      if request.method =="POST":
        suspect = suspect()
        suspect.suspect_name = request.POST['FName']
        suspect.suspect_last_name = request.POST['LName']
        suspect.suspect_father_name = request.POST['FatherName']
        suspect.suspect_mother_name = request.POST['MotherName']
        suspect.gender = request.POST['Gender']
        suspect.content = request.POST['content']
        print(suspect.suspect_name)

        suspect.save()

      context = {
        "title":member.member_name,
        "instance":member,
      }

    return render(request,'blog/update.html',context)    

我将不胜感激任何帮助

【问题讨论】:

    标签: django ajax forms sql-update


    【解决方案1】:

    我会给你一个简单的例子,你可以根据你的情况进行扩展。

    在用户拥有更新个人资料链接的模板中:

    <a href="{% url 'Profile-Update' %}"> Update Profile </a>
    

    在你的 urls.py 中

    path('update_profile/', views.ProfileUpdate, name='Profile-Update')
    

    在views.py中

    
    def ProfileUpdate(request):
      current_user = request.user
      if request.method == 'POST':
        get_username = request.POST.get('username', '').strip()
        suspect.objects.filter(pk=current_user.pk).update(username=get_username)
        return HttpResponse('Profile Updated')
      else:
        return render(request, 'prorile_update_form.html', {'current_user': current_user})
    

    在 prorile_update_form.html 中:

    
    <form class="update_profile">
    {{ csrf_token }}
      <input type="text" name="username" value="{{ current_user.username }}">   
      <button class="submit_update">Save changes</button>
    </form>
    <!-- So the current user username will be displayed on the input as a value -->
    
    <script type="text/javascript">
    $('.submit_update').on('click', function(){
                  $.ajax({
                 url: '/update_profile/',
                 method : 'POST',
                 data: $('.update_profile').serialize(),
                 beforeSend: function() {
                  // things to do before submit
                 },
                 success: function(response) {
    
                  alert(response)
                  }
                  });
      return false;
    
    });
    </script>
    
    

    如果用户有不同的模型可以更新,那么您可能希望将表单的 id 作为变量传递给 url,如下所示:

    path('update_profile/<int:pk>', views.ProfileUpdate, name='Profile-Update')
    

    你在你的视图中解释变量是这样的:

    def ProfileUpdate(request, pk):
    

    您可以使用 pk 获取所需的模型,然后根据您将提供的表单进行所有所需的更新。

    【讨论】:

    • 我将编辑我的问题并添加在函数和模板上完成的更新你能看看并告诉我错误是什么吗?因为系统显示错误。
    • 如果我对您的第一个问题的回答是正确的,您能接受吗?
    • 如何检查它是否适合我?我确实更新了问题并按顺序添加了功能,如果您可以检查它并告诉我它是否写错以及错误在哪里
    • 我会接受您的回答并感谢您的时间和帮助,但希望您能回答更新后的问题
    • 我过去的错误提示是,进入更新页面是通过一个名为更新详细信息的按钮,然后用户可以根据选定的 id 更新表单上存在的数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2021-04-14
    相关资源
    最近更新 更多