You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django表单数据无法保存问题求助(附相关代码)

Troubleshooting Django Form Data Not Saving Issue

Hey there, let's dig into why your Django form isn't saving data properly. Looking at the code snippets you shared, here are the key issues and fixes to get this working:

1. Fix the Incomplete View Logic in views.py

Your save view is cut off, and the core issue is likely missing proper form handling. Here's the complete, corrected implementation:

from django.shortcuts import render, redirect
from .forms import SaveForm
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def save(request):
    if request.method == 'POST':
        # Instantiate form with POST data
        save_form = SaveForm(request.POST)
        # Validate form data before saving
        if save_form.is_valid():
            save_form.save()
            # Redirect to a success page after saving (replace with your actual URL)
            return redirect('/app/student-list/')
    else:
        # Return empty form for GET requests
        save_form = SaveForm()
    # Render the form page (replace 'your_form_template.html' with your template name)
    return render(request, 'your_form_template.html', {'form': save_form})

Note: Using @csrf_exempt is not recommended for production. Instead, add the Django CSRF token to your HTML form (see next point) and remove this decorator.

2. Improve the HTML Form

Your form is missing the required CSRF token (a Django security requirement). Add it, and consider using Django's built-in form rendering for better error handling:

<form action="/app/save" method="POST">
    {% csrf_token %} <!-- Add this line for CSRF protection -->
    <!-- Manual field rendering (as you had) -->
    <input id="classname" name="classname" placeholder="Class Name">
    <input id="score" name="score" placeholder="Score">
    <input id="course" name="course" placeholder="Course">
    <button type="submit">SEND</button>
</form>

Alternatively, use Django's automatic form rendering to save time and get built-in error messages:

<form action="/app/save" method="POST">
    {% csrf_token %}
    {{ form.as_p }} <!-- Renders all form fields with labels -->
    <button type="submit">SEND</button>
</form>

3. Verify Model-Form Field Matching

Double-check that your Student model has exactly the fields specified in SaveForm (classname, score, course), and that their data types match what users input. For example:

  • If score is an IntegerField in the model, users must enter numbers (not text) for the form to validate.
  • Ensure none of these fields are marked as blank=False/null=False in the model if users might leave them empty (adjust form or model accordingly).

4. Debug Validation Failures

If the form still won't save, add debug code to see why validation is failing:

if save_form.is_valid():
    save_form.save()
    return redirect('/app/student-list/')
else:
    # Print errors to your terminal for debugging
    print("Form errors:", save_form.errors)

This will show you exactly which fields are failing validation and why.


内容的提问来源于stack exchange,提问作者user9673470

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:20:57