jQuery回复保存功能异常求助:提示成功但数据库未实际存储
Let's break down why your reply isn't saving to the database even though you're getting a "Sent" alert. Since the success alert is triggering, your backend is returning "True" — which means the try block is executing. So we need to dig into what's happening inside that block and ensure the data is actually being persisted.
1. Verify Your Model Has the Correct Field
First, double-check your SendmessageAdmin model. If you're assigning messages.message_reply = reply_message, make sure the model actually has a message_reply field. For example:
class SendmessageAdmin(models.Model): # Your existing fields message_reply = models.TextField(blank=True, null=True) # Or CharField, depending on your needs # ...
If the field name is wrong (e.g., you named it reply_message in the model), the assignment will silently fail, and save() won't update anything in the database.
2. Log What's Happening in the Backend
Your current except block is too broad — it catches all errors but gives you no details. Let's add logging to see exactly what's going on:
import logging logger = logging.getLogger(__name__) @csrf_exempt def admin_message_replied(request): reply_id = request.POST.get("id") reply_message = request.POST.get("message") logger.info(f"Received data: ID = {reply_id}, Message = {reply_message}") try: messages = SendmessageAdmin.objects.get(id=reply_id) logger.info(f"Found object: ID {messages.id}, current reply: {messages.message_reply}") messages.message_reply = reply_message messages.save() logger.info(f"After save, reply is now: {messages.message_reply}") return HttpResponse("True") except Exception as e: logger.error(f"Error during save: {str(e)}") return HttpResponse("False")
Check your Django logs (usually in django.log or your console) for these messages. This will tell you:
- If the correct ID and message are being received
- If the
SendmessageAdminobject is being found - If the
message_replyfield is being updated before save
3. Validate Frontend Data is Correct
Before sending the AJAX request, confirm the values you're passing are accurate. Add a console.log in your frontend code to check:
.done(function(response){ console.log("Sent ID:", id, "Sent Message:", message); console.log("Backend response:", response); if(response=="True"){ alert("Sent") } else{ alert("Not Sent") } // location.reload(); // Temporarily comment this out to avoid immediate page refresh })
Also, open your browser's DevTools > Network tab, find the POST request to admin_message_replied, and check the Form Data section to ensure id and message are being sent correctly. Sometimes whitespace in the id (from the table cell) can cause issues — if that's the case, use $.trim(id) to clean it up.
4. Fix CSRF Handling (More Secure Alternative)
While you're using @csrf_exempt, it's better practice to include the CSRF token in your AJAX request (and remove @csrf_exempt from the view). This avoids potential middleware conflicts:
$.ajax({ url:'{% url 'admin_message_replied' %}', type:'POST', data:{ id:id, message:message, csrfmiddlewaretoken: '{{ csrf_token }}' // Add this line }, })
Then remove @csrf_exempt from your Django view — this is safer and aligns with Django's security best practices.
5. Check for Overridden save() Method
If you've overridden the save() method in your SendmessageAdmin model, make sure you're calling super().save(*args, **kwargs) at the end. For example:
def save(self, *args, **kwargs): # Your custom logic here super().save(*args, **kwargs) # Don't forget this line!
Without calling the parent save() method, the changes won't be persisted to the database.
6. Rule Out Transaction Issues
Django auto-commits changes by default, but if you're using transactions elsewhere (e.g., in a parent view or middleware), the save might be rolled back. Check if there's any transaction management code that could be preventing the commit.
Once you work through these steps, you should be able to pinpoint exactly where the data flow is breaking. Most likely, it's either a misnamed model field, incorrect data being sent from the frontend, or a silent failure in the save() process.
内容的提问来源于stack exchange,提问作者user14925421

