Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

python - How to make it such that if there are errors in the form, all the data I have keyed into the field remains and only the error pops out

How to make it such that if there are errors in the form, all the data I have keyed into the field remains and the error shows for me to edit what I need to edit.

Because it is very user-unfriendly if people press submit, and everything they have previously typed has to be retyped again due to an error that caused them to need to submit the form again.

just like when we post a stackoverflow question, if there are errors in our question eg time limit, whatever we have typed previously remains

Let me know if you require more code.

html

   <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %}
   <div class="form-group">
    <label for="id_title">Title</label>
    <input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus>
   </div>
   <button class="submit-button btn btn-lg btn-primary btn-block" type="submit">Submit</button>

  </form>

  {% if form.errors %}
  {% for field in form %}
      {% for error in field.errors %}
          <div class="alert alert-danger">
              <strong>{{ error|escape }}</strong>
          </div>
      {% endfor %}
{% endif %}
    

views.py

def create_blog_view(request):
    context = {}
    user = request.user
    if request.method == 'POST':
        form = CreateBlogPostForm(request.POST or None, request.FILES or None)    
        if form.is_valid():
            obj.save()
            return redirect('HomeFeed:main')
        else:
            context['form'] = form
    return render(request, "HomeFeed/create_blog.html", context)

question from:https://stackoverflow.com/questions/65931151/how-to-make-it-such-that-if-there-are-errors-in-the-form-all-the-data-i-have-ke

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are rendering the fields manually by writing the tags. When you render using the form instance Django automatically sets the value attributes with the previous values. You can use {{ form.as_table }}, {{ form.as_p }}, {{ form.as_ul }}. You can also render fields individually using {{ form.title }} where title is the field name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...