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

Django技术问询:文件上传至PostgreSQL后无法修改模型is_recorded与has_issue字段值

Troubleshooting Your Upload Form & Database Field Update Issues

Let's break down the problems you're facing and fix them step by step:

1. The Root Cause of Your except Block Trigger

Your broad except: clause is hiding the actual error that's preventing your fields from updating. Plus, your logic for fetching the Upload object is risky—using Upload.objects.get(is_recorded=False) will throw a MultipleObjectsReturned exception if there's more than one unrecorded upload in your database, which is almost certainly triggering the generic error message.

2. Step-by-Step Fixes

Fix 1: Capture Specific Exceptions & Debug Details

First, replace your generic except: with code that captures and displays the actual error. This will tell you exactly what's breaking:

import traceback  # Add this import at the top

def upload_view(request):
    error_message = None
    success_message = None
    form = UploadForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        # Get the newly saved object directly (no need to query later!)
        obj = form.save()
        form = UploadForm()
        try:
            recorded, issue, success_message, error_message = upload_csv_to_DB(obj)
            obj.is_recorded = recorded
            obj.has_issue = issue
            obj.save()
        except Exception as e:
            # Show the actual error instead of a generic message
            error_message = f'Error: {str(e)}'
            # Print full traceback to your console for debugging
            traceback.print_exc()
    context={
        'form': form,
        'success_message': success_message,
        'error_message': error_message,
    }
    return render(request, 'upload/upload.html', context)

Fix 2: Fetch the Correct Upload Object

Instead of querying for is_recorded=False, use the object returned by form.save() directly. This guarantees you're modifying the exact file that was just uploaded, not an old or duplicate entry.

Fix 3: Validate Your upload_csv_to_DB Function

Double-check that this function is actually returning four values in the correct order: (recorded: bool, issue: bool, success_msg: str, error_msg: str). A common mistake here is returning values in the wrong order, which would assign incorrect values to is_recorded and has_issue.

Also, verify that the function properly handles the file path from obj.file_name.path—if the file can't be found or read, it'll throw an exception that your updated except block will now show you.

Fix 4: Check for Database Transaction Issues

If upload_csv_to_DB uses raw SQL or SQLAlchemy (for pd.to_sql), make sure it's committing the transaction. For example, if you're using a SQLAlchemy engine, you might need to add:

# Inside upload_csv_to_DB after pd.to_sql
engine.commit()

Django's ORM handles transactions automatically, but external database operations might not.

3. Additional Debug Tips

  • Enable Django's debug mode (DEBUG = True in settings.py) to see full error pages when something breaks.
  • Check your Django console logs—they'll show the traceback from traceback.print_exc() to pinpoint exactly where the failure happens.
  • Test upload_csv_to_DB independently with a sample file to confirm it returns the correct values and doesn't throw unexpected exceptions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:33:11