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

Python Django新手求助:如何将数据传入views.py并POST至数据库

Fixing Your Django CreateView for POST Data Saving

Hey there! Let's work through your code issues and get that Employee data saving correctly via POST requests—since you're new to Django, I'll break this down clearly.

First, Let's Spot the Problems in Your Current Code

  • You've got a global salary = 212 variable, and you're setting self.object.name = salary in form_valid. This doesn't make sense (you're assigning a number to the employee's name field!) and it completely ignores the actual data the user submits via the form.
  • When calling super(), you're using ModelFormMixin instead of your view's actual parent class. This can break the default CreateView behavior that handles form saving and redirects.
  • Your form_valid override is unnecessary for basic form saving—CreateView already handles POST requests and saves valid form data automatically.

Solution 1: Basic Form Saving (No Custom Logic)

If you just want users to submit an employee form (with id, name, salary) and save it directly to the database, you don't need the custom form_valid method at all. Here's the cleaned-up code:

from django.views.generic.edit import CreateView
from .models import Employee

class EmployeeCreateView(CreateView):
    # Specify the fields you want the form to include
    fields = ('id', 'name', 'salary')
    # Link to your Employee model
    model = Employee
    # Optional: Add a success URL to redirect after saving (replace with your actual URL)
    # success_url = '/employees/'

Solution 2: Custom Logic Before Saving

If you do need to modify data before saving (e.g., set a default salary, or pull extra data from the request), here's how to properly override form_valid without breaking things:

from django.views.generic.edit import CreateView
from .models import Employee

class EmployeeCreateView(CreateView):
    fields = ('id', 'name')  # Remove 'salary' if you don't want users to input it
    model = Employee

    def form_valid(self, form):
        # Create the object but don't save to DB yet
        self.object = form.save(commit=False)
        
        # Add your custom logic here:
        # Example 1: Set a default salary
        self.object.salary = 212
        # Example 2: Pull salary from a POST parameter (if it's sent outside the form)
        # self.object.salary = self.request.POST.get('salary', 0)
        
        # Save the modified object to the database
        self.object.save()
        
        # Correctly call the parent class's form_valid method to handle redirects
        return super().form_valid(form)

Next Steps to Make This Work

  1. Create a Template: Django expects a template named employee_form.html (in your app's templates folder) to render the form. Here's a simple version:
<form method="post">
    {% csrf_token %}
    <!-- Render all form fields as paragraphs -->
    {{ form.as_p }}
    <button type="submit">Save Employee</button>
</form>
  1. Add a URL Route: In your app's urls.py, link the view to a URL so users can access the form:
from django.urls import path
from .views import EmployeeCreateView

urlpatterns = [
    path('employees/create/', EmployeeCreateView.as_view(), name='employee-create'),
]

Key Takeaways

  • For basic form saving, let Django's CreateView do the heavy lifting—no need to override form_valid.
  • If you need custom logic, always call super().form_valid(form) at the end to preserve default behavior.
  • Avoid hardcoding values that should come from user input or the request.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:06:06