Django项目POST提交表单无响应问题排查求助
Let’s break down the issues preventing your form from submitting and saving data—there are a few small but critical fixes needed:
1. Incorrect Submit Button Type
Your form’s submit button uses type="button", which is just a clickable button that doesn’t trigger form submission by default. You need to change it to type="submit" to tell the browser to send the form data to your server.
Fix in sign.html:
<!-- Replace this line --> <input type="button" value="Submit"> <!-- With this --> <input type="submit" value="Submit">
2. Mismatched Model Field Name
Your Comment model has a field named comments (plural), but your view is trying to save data to a field named comment (singular), and your form uses {{form.comment}}. This mismatch would cause a database error once the form actually submits.
Fix in models.py:
Rename the model field to match your form and view:
class Comment(models.Model): name=models.CharField(max_length=20) comment=models.TextField() # Changed from "comments" to "comment" date_added=models.DateTimeField(default=timezone.now) def __str__(self): return self.name
3. Missing redirect Import
Your sign view tries to use redirect() but doesn’t import it from Django’s shortcuts. This would throw a NameError once the form validation passes.
Fix in views.py:
Add redirect to your imports:
from django.shortcuts import render, redirect # Added redirect here from .models import Comment from .forms import CommentForm
4. Redundant Manual Comment Creation
You’re manually creating a Comment object using request.POST data, but since you’re using a form, you can simplify this by calling form.save() directly (this is safer, as it uses the validated form data instead of raw POST data).
Simplified sign view in views.py:
def sign(request): if request.method=='POST': form = CommentForm(request.POST) if form.is_valid(): form.save() # Let the form handle saving the data return redirect('index') else: form = CommentForm() context={'form' : form} return render(request,'guestbook/sign.html',context)
Final Check: Ensure Your Form is Properly Linked to the Model
Make sure your CommentForm (in forms.py) is a ModelForm tied to your Comment model, so it automatically maps to the correct fields:
from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name', 'comment']
After applying these fixes, your form should submit correctly, validate user input, and save comments to the database.
内容的提问来源于stack exchange,提问作者Compoot

