I want to prevent rendering empty forms if my froms is invalid. I want it will render with previous data those typed in each fields. Right now it’s rendering empty forms if my forms is invalid.
here is my code:
#html
<form method="POST">
{% csrf_token %}
{{form}}
<button class="btn btn-primary" type="submit">Submit</button>
</form>
#froms.py:
class CommentFrom(forms.ModelForm):
captcha = CaptchaField()
class Meta:
model = BlogComment
fields = ['name','email','comment',]
widgets = {
'name': forms.TextInput(attrs={'class':'form-control','placeholder': 'name'}),
'email': forms.TextInput(attrs={'class':'form-control','placeholder': 'email'}),
'comment': forms.Textarea(attrs={'class':'form-control','placeholder': 'comment'}),
}
views.py
if form.is_valid():
comment = form.save(commit=False)
comment.blog = blog
comment.save()
messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval')
return redirect(reverse('blog-detail', kwargs={'slug':slug}))
else:
form = CommentFrom()
messages.add_message(self.request, messages.INFO, 'Captcah verification failed')
return redirect(reverse('blog-detail', kwargs={'slug':slug}))