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 = 212variable, and you're settingself.object.name = salaryinform_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 usingModelFormMixininstead of your view's actual parent class. This can break the default CreateView behavior that handles form saving and redirects. - Your
form_validoverride 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
- Create a Template: Django expects a template named
employee_form.html(in your app'stemplatesfolder) 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>
- 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
CreateViewdo the heavy lifting—no need to overrideform_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
相关产品推荐
相关产品推荐

