How can I validate a post request from an raw HTML form (No django form used)

雨燕双飞 提交于 2021-02-18 19:43:14

问题


def update(request, property_id):
    obj = get_object_or_404(PropertyModel, property_id=
    form = PropertyModelForm(request.POST or None, instance=
    if form.is_valid():
        form.save()
    template = 'form.html'
    context = {
        'form': form
    }
    return render(request, template, context)

have done using Django model from but want to do it using HTML form


回答1:


I'd recommend you to use Django forms but if that's not an option you can go ahead and use Javascript and manually checking on the views, here's an extremely rough example.

html form

<form action="{% url 'some-url' %}" method='post'>
    <input type="email" id='email' name='email'>
    <input type='password' id='passowrd' name='password'>
    <button type="button" onclick="Validate()">submit</button>
</form>

java script validation

function validate(){
    if ($("#email").val() == ""){
        alert("email field is required");
    }   
    if ($("#password").val().length < 8){
        alert("password should be over 8 characters");
    }   
}

behind the scenes views

from validate_email import validate_email

def myview(request):
   email = request.POST.get('email') 
   password = request.POST.get('password')

   if validate_email(email):
      if len(password) > 8:
        print("both the conditions met")
      else:
        messages.error("password should be over 8 characters")
        return redirect("url")
    else:
        messages.error("valid email is required")
        return redirect("url")


来源:https://stackoverflow.com/questions/59486180/how-can-i-validate-a-post-request-from-an-raw-html-form-no-django-form-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!