提交表单时向success.html页面传递成功消息的实现方法
success.html After Form Submission in Django Hey there! Let's get that success message showing up on your success.html page after form submission. I'll walk you through two reliable methods, plus tweak a couple of small issues in your existing code to make it more robust.
Method 1: Use Django's Built-in messages Framework (Recommended)
Django's messages framework is made exactly for this kind of scenario—passing temporary, one-time messages between requests. Here's how to set it up:
Step 1: Update Your View Code
First, import the messages module and modify your form_valid method to add the success message. I'll also fix the logids logic in your original code (right now it loops through all Logs and ends up with the last ID, which can be simplified to a single query):
from django.contrib import messages from django.views.generic.edit import FormView class SuccessView(FormView): template_name = 'success.html' form_class = QuestForm # Pro tip: Use a named URL instead of hardcoding, e.g., reverse('success') # Make sure your urls.py has a name for this view's URL pattern success_url = '/success/' def form_valid(self, form): # Get the latest Log entry directly (no need to loop through all) last_log = Logs.objects.last() # Handle edge case where there are no Log entries yet logids = last_log.id if last_log else 0 q1 = form.cleaned_data['ques'] Quest.objects.create(logid=logids, status=0, question=q1) # Add the success message to the request messages.success(self.request, "form successfully submitted") return super().form_valid(form)
Step 2: Display the Message in success.html
Add this snippet to your template to render the message:
{% if messages %} {% for message in messages %} <div class="alert alert-success"> {{ message }} </div> {% endfor %} {% endif %}
Method 2: Pass the Message Directly via Template Context
If you prefer not to use the messages framework, you can add the message to the template context directly. Since SuccessView renders success.html after form validation, we can override get_context_data to inject the message:
Step 1: Update the View
class SuccessView(FormView): template_name = 'success.html' form_class = QuestForm success_url = '/success/' def form_valid(self, form): last_log = Logs.objects.last() logids = last_log.id if last_log else 0 q1 = form.cleaned_data['ques'] Quest.objects.create(logid=logids, status=0, question=q1) # Store the message as an instance variable to use later self.success_message = "form successfully submitted" return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Add the message to the context if it exists if hasattr(self, 'success_message'): context['success_message'] = self.success_message return context
Step 2: Display the Message in success.html
{% if success_message %} <div class="alert alert-success"> {{ success_message }} </div> {% endif %}
Quick Fixes for Your Original Code
- The loop over
Logs.objects.all()to getlogidsis inefficient—usingLogs.objects.last()retrieves the latest ID in one query instead of loading all entries. - Avoid hardcoding URLs like
success_url='success'—use Django'sreverse()function with a named URL pattern to make your code more maintainable (e.g.,success_url = reverse('success')).
内容的提问来源于stack exchange,提问作者Anjitha

