
@login_required
def expense_edit_view(request, pk):
    expense = get_object_or_404(Expense, pk=pk)
    if request.method == 'POST':
        try:
            category_id = request.POST.get('category')
            amount = request.POST.get('amount')
            date = request.POST.get('date')
            description = request.POST.get('description')
            payment_method_id = request.POST.get('payment_method')
            
            category = get_object_or_404(ExpenseCategory, pk=category_id)
            payment_method = get_object_or_404(PaymentMethod, pk=payment_method_id) if payment_method_id else None
            
            expense.category = category
            expense.amount = amount
            expense.date = date or expense.date
            expense.description = description
            expense.payment_method = payment_method
            
            if 'attachment' in request.FILES:
                expense.attachment = request.FILES['attachment']
            
            expense.save()
            messages.success(request, _('Expense updated successfully.'))
        except Exception as e:
            messages.error(request, _('Error updating expense: ') + str(e))
            
    return redirect('expenses')
