有没有办法验证没有form tag和forms.py的字段?

时间:2017-11-20 06:22:16

标签: jquery python html ajax django

正如标题所说的那样,我一直在研究如何在django的html上为每个字段添加错误消息,因为我们被教导在不使用forms.py或form标签的情况下执行ajax。这有解决方案吗?或者我是否需要为每个人创建表单? 例如:

编辑帐户功能html

{% for user in users %} 
<!--start EDIT MODAL -->
<div id="editAcct-{{user.id}}" class="modal fade" role="dialog" aria-hidden="true">


  {% csrf_token %}
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="form-horizontal form-label-left input_mask">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close" required><span aria-hidden="true">×</span>
          </button>
          <h3 class="modal-title" id="myModalLabel">Edit {{ user.username }}</h3>
        </div>

              <input type="hidden" name="pkid" id="pkid" class="form-control" value="{{ user.id }}"> 
        <div class="modal-body">
          <div class="form-group">
            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="id-num">ID Number
            </label>
            <div class="col-md-8 col-sm-6 col-xs-12">
              <input type="number" name="id-num" id="id-num-{{ user.id }}" class="form-control" value="{{ user.profile.employeeID }}" required> 
            </div>

          </div>
          <div class="form-group">
            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">First Name
            </label>
            <div class="col-md-8 col-sm-6 col-xs-12">
              <input type="text" id="first-name-{{ user.id }}" name="first-name" class="form-control" value="{{ user.first_name }}" required>
            </div>
          </div>
          <div class="form-group">
            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Last Name
            </label>
            <div class="col-md-8 col-sm-6 col-xs-12">
              <input type="text" id="last-name-{{ user.id }}" name="last-name" class="form-control" value="{{ user.last_name }}" required>
            </div>
          </div>
          <div class="form-group">
            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="user-name">Username
            </label>
            <div class="col-md-8 col-sm-6 col-xs-12">
              <input type="text" id="user-name-{{ user.id }}" name="user-name" class="form-control" value="{{ user.username }}" required>
            </div>



          </div>



          <div class="form-group">
            <label for="middle-name" class="control-label col-md-3 col-sm-3 col-xs-12">Email</label>
            <div class="col-md-8 col-sm-6 col-xs-12">
              <input id="email-{{ user.id }}" class="form-control" type="email" name="email" value="{{ user.email }}" required>
            </div>
          </div>
        </div>
        <div class="modal-footer">
         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="submit" onClick="editAcctAjax({{ user.id }})" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>

  </div>
</div>
{% endfor %}

<!-- end EDIT MODAL -->

ajax javascript代码

<script>

    function editAcctAjax(id){
      var employeeid = document.getElementById('id-num-' + id).value;
      var firstname = document.getElementById('first-name-' + id).value;
      var lastname = document.getElementById('last-name-' + id).value;
      var username = document.getElementById('user-name-' + id).value;
      var email = document.getElementById('email-' + id).value;
        $.ajax({url: '/editModal/?pkid='+ id + '&id-num=' + employeeid + '&first-name=' + firstname + '&last-name=' + lastname + '&username=' + username + '&email=' + email, 
            success: function(data){
              window.location.reload();

              // $("#testRefresh").replaceWith($("#testRefresh",$(data)));
              // window.location.reload();

            },
             error: function(data) { 
                alert("invalid!");
            }    
            // error:function(data){
            //   alert("invalid!");
            // }
        });
    }
</script>

views.py for edit account

def editModal(request):

JSONer = {}
valid = True
parsedData = urlparse.urlparse(request.get_full_path())
pkid = (urlparse.parse_qs(parsedData.query)['pkid'][0])
idnum = (urlparse.parse_qs(parsedData.query)['id-num'][0])
firstname = (urlparse.parse_qs(parsedData.query)['first-name'][0])
lastname = (urlparse.parse_qs(parsedData.query)['last-name'][0])
username = (urlparse.parse_qs(parsedData.query)['username'][0])
email = (urlparse.parse_qs(parsedData.query)['email'][0])
error_msg1 = "empty"
error_msg2 = "empty"
context = {
'valid':valid,
'error_msg1':error_msg1,
'error_msg2':error_msg2,

}


if User.objects.filter(id=pkid).count() > 0:

    if Profile.objects.filter(Q(employeeID=idnum) & ~Q(user_id=pkid)).count() > 0:
        valid = False
        error_msg1 = "id is taken"
        print("id is already taken!")
    if User.objects.filter(Q(username = username) & ~Q(id=pkid)).count() > 0:
        valid = False
        error_msg2="username is taken"
        print("username is taken")
        messages.error(request,'Username is taken!',extra_tags="sameuser")
    if User.objects.filter(Q(email = email) & ~Q(id=pkid)).count() > 0:
        valid = False
        print("email is already taken!")
    if valid == False:
        response = HttpResponse(status=401)
        response['Content-Length'] = len(response.content)
        return response
    else:
        userID = User.objects.filter(id=pkid)[0]
        userID.profile.employeeID = idnum
        userID.first_name = firstname
        userID.last_name = lastname
        userID.username = username
        userID.email = email
        userID.save()
        messages.success(request,"Successfully updated account!")
    return HttpResponse(json.dumps(JSONer),context)


return HttpResponse(json.dumps(JSONer),context)

1 个答案:

答案 0 :(得分:0)

您仍然可以使用表单类仅在后端验证

views.py

def editModal(request):
    form = UserForm(request)
    if form.is_valid():
        # Do something
    else:
        # Do something else

使用表单类编写验证规则     https://docs.djangoproject.com/en/1.11/ref/forms/validation/