I have a modal with a form in it. The issue is that on invalid form it does return the form errors but it also closes the modal dialog box by rendering the home page again. It is also the home page so the return render is needed for the logging in.
How would I just return to the screen if the post fails.
def index(request):
context = {}
if request.method == "POST":
print(request.POST)
form = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user)
if form.is_valid():
form.save()
return redirect('home')
else:
form = UserProfileForm()
context['form']= form
return render(request, "home.html", context)
modal
{% block content %}
<div id="editProfile" tabindex="-1" role="dialog" aria-labelledby="editProfilelCenterTitle" aria-hidden="true">
<div role="document">
<div >
<div >
<h5 id="editProfileLongTtitle">Edit Profile</h5>
<button type="button" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div >
{% include 'form.html' %}
</div>
</div>
</div>
</div>
{% endblock %}
form.html
{% block content %}
<form method = "POST" action='.' enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
{% endblock %}
home.html
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
{% if user.is_authenticated %}
<div >
{% include 'editProfileModal.html' %}
<div class='row'>
{% include 'sidebar.html' %}
</div>
</div>
{% else %}
<p>You are not logged in</p>
<a href="{% url 'login' %}">Log In</a>
<a href="{% url 'signup' %}">Sign up</a>
{% endif %}
{% endblock %}
CodePudding user response:
You need shows the modal while you're sending a POST request and the view don't send the redirect. You can try the next poor solution. It's ugly but can work:
def index(request):
context = {'is_post': False}
if request.method == "POST":
context['is_post'] = True
form = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user)
if form.is_valid():
form.save()
return redirect('home')
else:
form = UserProfileForm()
context['form']= form
return render(request, "home.html", context)
{% block content %}
<div id="editProfile" tabindex="-1" role="dialog" ... >
<!-- your content ... -->
</div>
<!-- Do this after jQuery loaded -->
{% if is_post %}
<script type="text/javascript">
$(window).on('load', function() {
$('#myModal').modal('show');
});
</script>
{% endif %}
{% endblock %}
CodePudding user response:
You can simple return HttpResponse
with form errors.
from django.http import HttpResponse
if form.is_valid():
...
else:
return HttpResponse(form.errors.as_json())
CodePudding user response:
Try this:
def index(request):
context = {}
if request.method == "POST":
print(request.POST)
form = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user)
if form.is_valid():
form.save()
return redirect('home')
context['form']= form
return render(request, "home.html", context)