Django问题:表单提交更新用户数据时数据库数据被清空
Hey there, let's troubleshoot this frustrating issue where your Django view is wiping out database values instead of updating them with your form submissions—seeing a $2.00 price turn to $0.00 after hitting submit is no fun at all. Let's break down the most likely causes and how to fix them:
Common Causes & Fixes
1. Your form isn't actually receiving the submitted price value
First, let's rule out the simplest issue: your template might not be sending the price data correctly to the backend.
- Double-check that you're rendering the price field properly in your template. If you're using Django's form rendering, make sure you're using
{{ form.price }}(not a manually written input with a mismatchednameattribute). If you are writing the input manually, ensure thenameattribute exactly matches the field name in your form class (e.g.,name="price"). - Also confirm your form includes the
{% csrf_token %}tag—while this usually causes a 403 error instead of empty values, it's worth verifying to eliminate edge cases.
2. Form validation/cleaning is dropping the price value
You mentioned printing self.cleaned_data—let's use that to diagnose:
- If
cleaned_datadoesn't include thepricekey at all, that means the form never received the value (go back to checking your template). - If
cleaned_datahaspricebut it's empty or 0.00, your custom cleaning logic might be messing it up. For example, if you're stripping$symbols from the input:
A common mistake here is returning an empty value if the formatting fails, instead of raising adef clean_price(self): raw_price = self.cleaned_data.get('price') # If your input includes a $, make sure you're handling it correctly if raw_price and raw_price.startswith('$'): cleaned_price = raw_price.strip('$') try: return Decimal(cleaned_price) except ValueError: raise forms.ValidationError("Please enter a valid price (e.g., $3.00 or 3.00)") # Don't return None or empty here—if the field is required, let Django handle the error return raw_priceValidationErrorto alert the user. If you don't raise an error, Django might fall back to the field's default value (0.00) when saving.
3. Your view is saving a new object instead of updating the existing one
Make sure your view is passing the existing database instance to the form when handling POST requests. This is critical for updating instead of creating a new record:
def update_user_data(request, pk): # Fetch the existing user data record user_data = get_object_or_404(UserData, pk=pk) if request.method == 'POST': # Pass the instance to the form so it knows to update, not create form = UserDataForm(request.POST, instance=user_data) if form.is_valid(): print(form.cleaned_data) # Verify this has the correct price value form.save() return redirect('user_data_detail', pk=pk) else: form = UserDataForm(instance=user_data) return render(request, 'update_user_data.html', {'form': form})
If you forget the instance parameter, the form will create a new UserData object with default values (like 0.00 for price) instead of updating the existing one.
4. Accidental value reset in your view or form
Double-check your code for any lines that might be overwriting the price value before saving. For example, if you're using form.save(commit=False):
obj = form.save(commit=False) # Avoid lines like this! obj.price = 0.00 obj.save()
A stray line resetting the price could easily cause this issue.
Quick Diagnostic Steps
- In your view, add
print(request.POST)right after checking for POST method—this will show you exactly what data is being sent from the template. Ifpriceis missing here, fix the template. - If
request.POSThas the correct price butform.cleaned_datadoesn't, debug your form's cleaning methods. - Ensure
form.is_valid()returnsTruebefore saving—if it'sFalse, your form has errors that you should display in the template with{{ form.errors }}.
内容的提问来源于stack exchange,提问作者Micah Pearce

