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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…